2

我正在尝试用 Python 编写一个程序来检查输入的字符串是否按字母顺序(abcdearian)。程序需要忽略非字母字符,将大写字母视为小写字母。例如... abCde 是 abcdearian 而 eff!ort 是 abcdearian。现在该程序不会忽略非字母字符,但它确实将大写字母视为小写字母。但是,我希望程序打印原始输入,而不是转换后的输入。所以 abCde 在打印时应该显示为 abCde(而不是 abcde)。谢谢您的帮助!

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

3 回答 3

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:]) :
于 2012-11-26T01:16:27.670 回答
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)
于 2012-11-26T01:16:19.360 回答
0

这是另一种方式:

def is_abcdearian(s):
    import re
    s = s.lower()
    s = re.sub('[^a-z]', '', s)
    return s == ''.join(sorted(s))
于 2012-11-26T01:28:53.350 回答