如何检查字符串是否包含至少2位数字且没有空格?

时间:2016-04-23 23:00:10

标签: python python-3.x

我必须建立一个输入密码的程序。密码必须包含至少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()

5 个答案:

答案 0 :(得分: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.')

答案 1 :(得分:1)

要在字符串包含少于2位数时报告错误,您可以使用:

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

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

if password.isupper():

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

any(map(str.isupper, password))

答案 2 :(得分:0)

&#34;(...)没有空格且至少有2位数。&#34;

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

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

答案 3 :(得分:0)

用户正则表达式

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

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

正则表达式匹配javascript语法

答案 4 :(得分:-1)

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}')