简体   繁体   English

Python:如何忽略非字母字符并将所有字母字符都视为小写?

[英]Python: How to ignore non-letter characters and treat all alphabetic characters as lower case?

I'm trying to make a program in Python that checks if the inputted string is in alphabetical order (abcdearian). 我正在尝试使用Python创建一个程序,该程序检查输入的字符串是否按字母顺序(abcdearian)。 The program needs to ignore non-letter characters and treat capital letters as lowercase letters. 该程序需要忽略非字母字符,并将大写字母视为小写字母。 For example... abCde is abcdearian and eff!ort is abcdearian. 例如,abCde是abcdearian,而eff!ort是abcdearian。 Right now the program does not ignore non-letter characters, but it does treat capital letters as lowercase letters. 目前,该程序不会忽略非字母字符,但会将大写字母视为小写字母。 However, I want the program to print the original input, and not the converted one. 但是,我希望程序打印原始输入,而不是转换后的输入。 So abCde should show up as abCde (not abcde) when it is printed. 因此,在打印时,abCde应该显示为abCde(而不是abcde)。 Thanks for the help! 谢谢您的帮助!

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)

I'd try this: 我会尝试这样的:

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)

and if you are ambitious, you may try to replace: 如果您有雄心壮志,可以尝试更换:

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

with: 有:

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

Instead of calling string.lower() outside of the function, you could do it inside, like so: 您可以在内部执行此操作,而不是在函数外部调用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)

Here's another way: 这是另一种方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM