简体   繁体   中英

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). 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. 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. 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:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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