2015-06-26 164 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,但像你說的那樣,它仍然允許字符串,如「£*^$&^」這些不可接受的名字 –

相關問題