String Python字符串检查
有人能告诉我如何检查用户的输入是否包含数字,并且只包含数字和字母吗 以下是我到目前为止的情况:String Python字符串检查,string,python-3.x,numbers,String,Python 3.x,Numbers,有人能告诉我如何检查用户的输入是否包含数字,并且只包含数字和字母吗 以下是我到目前为止的情况: employNum = input("Please enter your employee ID: ") if len(employNum) == 8: print("This is a valid employee ID.") 我想在所有检查完成后打印最后一份报表。我只是不知道如何检查字符串 .alnum()测试字符串是否都是字母数字。如果您至少需要一个数字,则使用.isdigit()单
employNum = input("Please enter your employee ID: ")
if len(employNum) == 8:
print("This is a valid employee ID.")
我想在所有检查完成后打印最后一份报表。我只是不知道如何检查字符串 .alnum()
测试字符串是否都是字母数字。如果您至少需要一个数字,则使用.isdigit()
单独测试这些数字,并使用any()
查找至少一个:
>>> 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
参考资料:哇,太快了。非常感谢。有没有办法检查是否有一定数量的字母或数字?例如,如果employNum必须包含3个数字?@WhooCares:检查编辑。如果您想要更严格的检查,您可以查看正则表达式(如果您想让我写出来,请发表评论)
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.")