2013-10-29 139 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