2015-06-26 165 views
0

我想验证用户名称的输入。到目前为止,我可以阻止他们输入唯一的数字,并使用while循环重复提示。如何停止包含字母和数字的字符串被接受?如何检查字符串是否包含任何数字

这是我到目前为止有:

name = "" 
name = input("Please enter your name:") 
while name == "" or name.isnumeric() == True: 
    name = input("Sorry I didn't catch that\nPlease enter your name:") 

回答

3

使用anystr.isdigit

>>> any(str.isdigit(c) for c in "123") 
True 
>>> any(str.isdigit(c) for c in "aaa") 
False 

你的情况:

while name == "" or any(str.isdigit(c) for c in name): 
    name = input("Sorry I didn't catch that\nPlease enter your name:") 

或者您可以使用str.isalpha

如果字符串中的所有字符都是字母并且至少有一个字符,则返回true,否则返回false。

对于8位字符串,此方法与区域设置相关。

我会使用它像这样来验证这样的东西"Reut Sharabani"

while all(str.isalpha(split) for split in name.split()): 

    # code... 

它所做的是由空格分开的输入,并确保每个部分只有字母。

+1

为什么不使用'string.isalpha()'? –

+1

@Ben只因为标题,但你是对的:)添加。 –

+1

@ReutSharabani你能告诉我如何将str.isalpha()并入我的while循环吗?我用你的第一个例子Reut,但像你说的那样,它仍然允许字符串,如“£*^$&^”这些不可接受的名字 –

相关问题