【问题标题】:Python: How to ignore non-letter characters and treat all alphabetic characters as lower case?Python:如何忽略非字母字符并将所有字母字符视为小写?
【发布时间】:2012-11-26 01:11:02
【问题描述】:

我正在尝试用 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)

【问题讨论】:

  • 别想了,用字母做一个列表,检查字符串的字符是否不在列表中?

标签: python


【解决方案1】:

我会试试这个:

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

【讨论】:

  • 谢谢。正是我需要的。
【解决方案2】:

您可以在函数外部调用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)

【讨论】:

    【解决方案3】:

    这是另一种方式:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-22
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多