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()文字列がすべて英数字かどうかをテストします。少なくとも 1 つの数字が必要な場合は、数字を個別にテストし、少なくとも 1 つの数字.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.")

参考文献:任意の アルナムは 数字です

于 2013-10-29T05:06:20.270 に答える