0

有人能告诉我如何检查用户的输入是否包含数字并且只包含数字和字母吗?

这是我到目前为止所拥有的:

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

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

完成所有检查后,我想打印最后一条语句。我似乎无法弄清楚如何检查字符串。

4

2 回答 2

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
于 2013-10-29T05:05:07.740 回答
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.")

参考:任何 alnum isdigit

于 2013-10-29T05:06:20.270 回答