[英]Python exclude special characters and numbers
有一個更好的方法嗎?
我希望代碼檢測數字和特殊字符並打印:
“不允許數字” /“不允許特殊字符”
while True:
try:
x = input('Enter an alphabet:')
except ValueError:
print('sorry i do not understand that')
continue
if x in ('1', '2','3','4','5','6','7','8','9','0'):
print('Numbers not allowed')
continue
else:
break
if x in ('a', 'e', 'i', 'o', 'u'):
print ('{} is a vowel'.format(x))
elif x in ('A', 'E', 'I', 'O', 'U'):
print ('{} is a vowel in CAPS'.fotmat(x))
else:
print('{} is a consonant'.format(x))
一種方法是使用string
庫。
以下是一些偽代碼,它們假定輸入一次是一個字符:
import string
x = input('Enter an alphabet:')
if x in string.digits:
print('Numbers not allowed')
elif x not in string.ascii_letters:
print('Not a letter')
string.ascii_letters
是一個包含所有大寫和小寫字母的字符串:
print(string.ascii_letters)
#'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
同樣, string.digits
是包含所有數字的字符串:
print(string.digits)
#'0123456789'
您可以通過幾種方法來實現,但是pythonic方法在我看來就像這樣:
if any(char in string.punctuation for char in x) or any(char.isdigit() for char in x):
print("nope")
可能是這段代碼完成了工作。
while True:
x = ord(input('Enter an alphabet:')[0])
if x in range(ord('0'), ord('9')):
print('Numbers not allowed')
continue
if x not in range(ord('A'), ord('z')):
print('Symbols not allowed')
continue
if chr(x) in 'aeiou':
print('{} is a vowel'.format(chr(x)))
elif chr(x) in 'AEIOU':
print('{} is a vowel in CAPS'.format(chr(x)))
else:
print('{} is a consonant'.format(chr(x)))
continue
我們選擇數字,取消選擇除字母之外的任何字符,然后執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.