2013-10-29 92 views
0

有人可以告訴我如何檢查用戶的輸入是否包含數字,並且只包含數字和字母?Python字符串檢查

這裏是我到目前爲止有:

employNum = input("Please enter your employee ID: ") 

if len(employNum) == 8: 
    print("This is a valid employee ID.") 

我想打印的最後一條語句全部檢查完成之後。我似乎無法弄清楚如何檢查字符串。

回答

0
>>> employNum = input("Please enter your employee ID: ") 
Please enter your employee ID: asdf890 
>>> all(i.isalpha() or i.isdigit() for i in employNum) 
True 
>>> employNum = input("Please enter your employee ID: ") 
Please enter your employee ID: asdfjie-09 
>>> all(i.isalpha() or i.isdigit() for i in employNum) 
False 


>>> def threeNums(s): 
... return sum(1 for char in s if char.isdigit())==3 
... 
>>> def atLeastThreeNums(s): 
... return sum(1 for char in s if char.isdigit())>=3 
... 
>>> def threeChars(s): 
... return sum(1 for char in s if char.isalpha())==3 
... 
>>> def atLeastThreeChars(s): 
... return sum(1 for char in s if char.isalpha())>=3 
... 
>>> rules = [threeNums, threeChars] 
>>> employNum = input("Please enter your employee ID: ") 
Please enter your employee ID: asdf02 
>>> all(rule(employNum) for rule in rules) 
False 
>>> employNum = input("Please enter your employee ID: ") 
Please enter your employee ID: asdf012 
>>> all(rule(employNum) for rule in rules) 
False 
>>> employNum = input("Please enter your employee ID: ") 
Please enter your employee ID: asd123 
>>> all(rule(employNum) for rule in rules) 
True 
+0

哇,那是快。謝謝!還有一種方法來檢查是否有一定數量的字母或數字?例如,如果employNum必須包含3個數字? –

+0

@WhooCares:檢查編輯。如果你想要更嚴格的檢查,你可以看一下正則表達式(如果你想讓我把它寫出來,可以發表評論) – inspectorG4dget

0

.alnum()測試字符串是否都是字母數字。如果你需要至少一個數字,然後逐個用.isdigit()測試數字,並尋找使用any()至少一個可以發現:

employNum = input("Please enter your employee ID: ") 

if len(employNum) == 8 and employNum.isalnum() and any(n.isdigit() for n in employNum): 
    print("This is a valid employee ID.") 

參考文獻:anyalnumisdigit