[英]Python exclude special characters and numbers
Is there a better way to do this? 有一个更好的方法吗?
I want the code to detect numbers and special characters and print: 我希望代码检测数字和特殊字符并打印:
"numbers not allowed" / "special characters not allowed" “不允许数字” /“不允许特殊字符”
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))
One way is to use the string
library. 一种方法是使用string
库。
Here is some psuedocode, which assumes that the input is one character at a time: 以下是一些伪代码,它们假定输入一次是一个字符:
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
is a string that contains all the uppercase and lowercase letters: string.ascii_letters
是一个包含所有大写和小写字母的字符串:
print(string.ascii_letters)
#'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Likewise, string.digits
is a string that contains all of the digits: 同样, string.digits
是包含所有数字的字符串:
print(string.digits)
#'0123456789'
You could do it a couple of ways but the pythonic method seems to me to be like so: 您可以通过几种方法来实现,但是pythonic方法在我看来就像这样:
if any(char in string.punctuation for char in x) or any(char.isdigit() for char in x):
print("nope")
May be this code does the job. 可能是这段代码完成了工作。
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
We select numbers, deselect whatever character except letters and then does the job. 我们选择数字,取消选择除字母之外的任何字符,然后执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.