【问题标题】:Python - Check if a string contains a digit [duplicate]Python - 检查字符串是否包含数字[重复]
【发布时间】:2015-10-19 01:32:50
【问题描述】:

我正在制作一个使用 while True 循环来要求用户输入通过条件的密码的函数; min8-15max 个字符的长度,并且至少包含一个整数。我对如何正确检查整数的输入感到困惑。

我的程序:

def enterNewPassword():
    while True:
        pw = input('Please enter a password :')
        for i in pw:
            if type(i) == int:
                if len(pw) >= 8 and len(pw) <= 15:
                    break
        if int not in pw:
            print('Password must contain at least one integer.')
        if len(pw) < 8 or len(pw) > 15:
            print('Password must be 8 and no more than 15 characters in length.')
    return pw

【问题讨论】:

    标签: python input


    【解决方案1】:

    试试:

    if not any(c.isdigit() for c in pw)
    

    代替

    if int not in pw:
        print('Password must contain at least one integer.')
    

    int 是一个类型对象,您要检查字符 0-9 是否存在。

    【讨论】:

      【解决方案2】:

      您可以使用正则表达式,例如:

          import re
          password = "hello"
          matches = re.findall('[0-9]', password)
          if len(matches) < 1:
              print "Password must contain at least one integer"
      

      【讨论】:

      • 正则表达式对于这项任务来说太过分了。你可以用更少的开销来做any(digit in password for digit in '0123456789')any(char in '0123456789' for char in password)
      猜你喜欢
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 2013-11-20
      相关资源
      最近更新 更多