【问题标题】:How to check if a string contains at least 2 digits and no spaces?如何检查字符串是否包含至少 2 位数字且没有空格?
【发布时间】:2016-04-23 23:00:10
【问题描述】:

我必须构建一个程序,您可以在其中输入密码。密码必须至少包含 8 个字符,以字母开头,有大小写字母,不能有空格,并且至少有 2 位数字。

除了最后 2 条以外,我什么都没有了。

我尝试使用 for 循环查看是否有空格或数字,但它仅在整个密码由空格或数字组成时才有效。如果有数字或空格,如果打印出密码中包含多少个字符的错误消息,而不仅仅是有多少个数字或空格。我知道这是因为 for 循环而发生的,但我一直不知道如何解决它。

这是我目前所拥有的:

again = 'y'
while again == 'y':
minimum_characters = 8
error = 0
print('Password must contain 8 characters, start with a letter,')
print(' have no blanks, at least one uppercase and lowercase letter,')
print(' and must contain at least 2 digits.')
password = input('Enter a password: ')
passlength = len(password)

#validity checks for errors
if passlength < minimum_characters:
    error += 1
    print (error, '- Not a valid password. Must contain AT LEAST 8 characters. PW entered has', passlength, '.')

if not password[0].isalpha():
    error += 1
    print(error, '- The password must begin with a letter.')

if password.isalpha():
    error += 1
    print(error, '- The password must contain at least 2 digits.')

if password.isupper():
    error += 1
    print(error, '- You need at least one lower case letter.')

if password.islower():
    error += 1
    print(error,'- You need at least one upper case letter.')


again = input('Test another password? (Y or N): ')
again = again.lower()

【问题讨论】:

  • 另外,在谈到好的密码时,必须使用XKCD。请考虑是否真的需要大写字母、数字和空格。

标签: python python-3.x


【解决方案1】:
if " " in password:
    error += 1
    print(error, '- Not a valid password. It contains spaces.')

if len([x for x in pwd if x.isdigit()]) < 2:
    error += 1
    print(error, '- The password must contain at least 2 digits.')

【讨论】:

    【解决方案2】:

    用户正则表达式

    import re
    sequence = "1Sentence1e"
    if re.match("(?:\d.*?){2,}", sequence):
      print("Match!")
    else:
      print("Not match!")
    

    小提琴:http://tpcg.io/73SyIc

    正则表达式匹配javascript语法

    【讨论】:

      【解决方案3】:

      "(...) 没有空格且至少有 2 位数字。"

      一些用于计算任何字符/数字出现次数的选项。只需替换为您需要的内容(示例中的数字和空格):

      if any([x for x in password if x == " "]):
          # 1 or more spaces in password
      
      if password.count(" ") > 0:
          # 1 or more spaces in password
      
      if len([x for x in password if x.isdigit()]) < 2:
          # less than 2 digits
      

      【讨论】:

        【解决方案4】:

        当字符串少于2位时报错可以使用:

        if sum(map(str.isdigit, password)) < 2:
        

        另外,您对大写和小写字母的检查不正确:

        if password.isupper():
        

        检查是否所有字符都是大写的。要检查任何字符是否为大写,您可以使用:

        any(map(str.isupper, password))
        

        【讨论】:

        • 我会将 if map(lambda x: x.isdigit(), password).count(True) &lt; 2 更改为 if sum(map(lambda x: x.isdigit(), password)) &gt;= 2 - 它适用于 Python 2 和 3,您的版本不适用于 Python 3
        • 谢谢,看起来好多了。
        【解决方案5】:
        while True:
        try:
            text = input("Please enter 8 digits: ")
            number = int(text)
            if len(text) != 8:
                raise ValueError()
        except ValueError:
            print('Try once again')
        else:
            print(f'Correct, your number is: {number}')
        

        【讨论】:

        • 欢迎来到 Stack Overflow。虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
        • 这并不能解决 OP 的问题:检查“没有空格和至少 2 位数字
        猜你喜欢
        • 2016-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-25
        相关资源
        最近更新 更多