2012-11-26 88 views
2

我想在Python中制作一个程序,检查输入的字符串是否按字母顺序排列(abcdearian)。该程序需要忽略非字母字符并将大写字母视为小写字母。例如... abCde是abcdearian和effcort是abcdearian。 现在程序不会忽略非字母字符,但它确实将大写字母视为小写字母。但是,我想让程序打印原始输入,而不是转换后的输入。所以在打印时,abCde应该显示为abCde(而不是abcde)。谢谢您的帮助!Python:如何忽略非字母字符并将所有字母字符视为小写字母?

def isabcde(s): 
    for i in range(len(s) - 1): 
     if s[i] > s[i+1]: 
      return print(s, "is not abcdearian") 
    return print(s, "is abcdearian") 


while True: 
    try: 
     s = input("The string? ").lower() 
    except EOFError: 
     break 
    except TypeError: 
     break 
    isabcde(s) 
+0

关闭我的头顶,做一个清单,字母,并检查字符串的字符不在该列表? – arynaq

回答

3

我想试试这个:

def isabcde(s): 
    filtered = [i for i in s.lower() if i in 'abcdefghijklmnopqrstuvxyz'] 
    for i in range(len(filtered) - 1): 
     if filtered[i] > filtered[i+1]: 
      return print(s, "is not abcdearian") 
    return print(s, "is abcdearian") 

while True: 
    try: 
     s = input("The string? ") 
    except EOFError: 
     break 
    except TypeError: 
     break 
    isabcde(s) 

,如果你有雄心,您可以尝试更换:

for i in range(len(filtered) - 1): 
     if filtered[i] > filtered[i+1]: 

有:

if all([i[0] < i[1] for i in zip(filtered,filtered[1:]) : 
+0

谢谢。正是我需要的。 – Ace

1

与其说string.lower()之外的功能,你可以做到这一点里面,像这样:

def isabcde(s): 
    original = s 
    s = s.lower() 
    for i in range(len(s) - 1): 
     if s[i] > s[i+1]: 
      print(original, "is not abcdearian") 
      return 
    print(original, "is abcdearian") 

while True: 
    try: 
     s = input("The string? ") 
    except EOFError: 
     break 
    except TypeError: 
     break 
    isabcde(s) 
0

这里的另一种方式:

def is_abcdearian(s): 
    import re 
    s = s.lower() 
    s = re.sub('[^a-z]', '', s) 
    return s == ''.join(sorted(s)) 
相关问题