我正在尝试用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)
答案 0 :(得分: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:]) :
答案 1 :(得分: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)
答案 2 :(得分:0)
这是另一种方式:
def is_abcdearian(s):
import re
s = s.lower()
s = re.sub('[^a-z]', '', s)
return s == ''.join(sorted(s))