【问题标题】:Python String checkPython 字符串检查
【发布时间】:2013-10-29 05:01:07
【问题描述】:

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

这是我目前所拥有的:

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

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

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

【问题讨论】:

    标签: string python-3.x numbers


    【解决方案1】:

    .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

    【讨论】:

      【解决方案2】:
      >>> 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:查看编辑。如果你想要更严格的检查,你可以看看正则表达式(如果你想让我写出来,请评论)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      相关资源
      最近更新 更多