在Python中只允许使用字符? [英] Allow Only Alpha Characters in Python?
问题描述
我在写一个程序,它的一部分需要输入一个名称。
名称只能是字母和空格(例如,John Smith),它不能是John Smith1
如果输入了无效字符,我需要程序显示错误消息并重新处理问题。我有一切,但验证。我猜这是这样的吗?
name = str(input(What are the customers name?
while True:
如果:
print(你输入了一个无效的字符,只输入名字。
name = str(input(What are the customers name?))
else:
break
有人可以填写 ??? $ c / c> .org / library / stdtypes.html#str.isalpharel =nofollow>
isalpha()
字符串方法。
由于此人将输入带空格的名称,因此您有两个选项:
- (使用
split()
) - 利用
string.letters
例如:
>>> import string
> > string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
将''
以获取允许的字符列表。因为这是家庭作业,其余由你决定。
I am writing a program, part of it requires the input of a name. The name can only be alpha and spaces (eg. John Smith) it cannot be John Smith1 If an invalid character IS entered, I need the program to display an error message and reask the questions. I have got everything but the validation. I'm guessing it goes something like this?
name = str(input("What is the customers name? "))
while True:
if ??????????????????? :
print("You have entered an invalid character. Enter only name."
name = str(input("What is the customers name? "))
else:
break
Can someone please fill in the ?????
s to make the program work?
Try the isalpha()
method of strings.
Since the person will enter names with spaces, you have two options:
- Split the input by the space (use
split()
) - Take advantage of
string.letters
For example:
>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Combine that with a ' '
to get your list of allowed characters. Since this is homework, the rest is up to you.
这篇关于在Python中只允许使用字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!