[英]Python: How to ignore non-letter characters and treat all alphabetic characters as lower case?
我正在嘗試使用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)
我會嘗試這樣的:
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:]) :
您可以在內部執行此操作,而不是在函數外部調用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)
這是另一種方式:
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.