所以我必须创建验证密码是否的代码:
以下是代码:
def validate():
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif not password.isdigit():
print("Make sure your password has a number in it")
elif not password.isupper():
print("Make sure your password has a number in it")
else:
print("Your password seems fine")
break
validate()
我不确定出了什么问题,但是当我输入一个有号码的密码时 - 它一直告诉我我需要一个带有数字的密码。任何解决方案?
答案 0 :(得分:6)
您可以将re
模块用于正则表达式。
有了它,您的代码将如下所示:
import re
def validate():
while True:
password = raw_input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
validate()
答案 1 :(得分:3)
password.isdigit()
不检查密码是否包含数字,它会根据以下内容检查所有字符:
str.isdigit():如果字符串中的所有字符都是数字,则返回true 并且至少有一个角色,否则为假。
password.isupper()
不检查密码中是否有大写,它会根据以下内容检查所有字符:
str.isupper():如果字符串中的所有包含字符都是,则返回true 大写,至少有一个套管字符,否则为假。
要获得解决方案,请在 check if a string contains a number上查看问题并接受回答。
您可以构建自己的hasNumbers()
- 函数(从链接问题复制):
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
和hasUpper()
- 函数:
def hasUpper(inputString):
return any(char.isupper() for char in inputString)
答案 2 :(得分:2)
r_p = re.compile('^(?=\S{6,20}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])')
此代码将使用以下命令验证您的密码:
答案 3 :(得分:1)
您正在检查整个密码字符串对象上的isdigit和isupper方法,而不是字符串的每个字符。以下是检查密码是否符合您的特定要求的功能。它不使用任何正则表达式的东西。它还会打印输入密码的所有缺陷。
#!/usr/bin/python3
def passwd_check(passwd):
"""Check if the password is valid.
This function checks the following conditions
if its length is greater than 6 and less than 8
if it has at least one uppercase letter
if it has at least one lowercase letter
if it has at least one numeral
if it has any of the required special symbols
"""
SpecialSym=['$','@','#']
return_val=True
if len(passwd) < 6:
print('the length of password should be at least 6 char long')
return_val=False
if len(passwd) > 8:
print('the length of password should be not be greater than 8')
return_val=False
if not any(char.isdigit() for char in passwd):
print('the password should have at least one numeral')
return_val=False
if not any(char.isupper() for char in passwd):
print('the password should have at least one uppercase letter')
return_val=False
if not any(char.islower() for char in passwd):
print('the password should have at least one lowercase letter')
return_val=False
if not any(char in SpecialSym for char in passwd):
print('the password should have at least one of the symbols $@#')
return_val=False
if return_val:
print('Ok')
return return_val
print(passwd_check.__doc__)
passwd = input('enter the password : ')
print(passwd_check(passwd))
答案 4 :(得分:1)
使用正则表达式当然可以找到更简单的答案,但这是最简单的方法之一
from string import punctuation as p
s = 'Vishwasrocks@23' #or user input is welcome
lis = [0, 0, 0, 0]
for i in s:
if i.isupper():
lis[0] = 1
elif i.islower():
lis[1] = 1
elif i in p:
lis[2] = 1
elif i.isdigit():
lis[3] = 1
print('Valid') if 0 not in lis and len(s) > 8 else print('Invalid')
答案 5 :(得分:1)
使用普通方法最简单的python验证
password = '-'
while True:
password = input(' enter the passwword : ')
lenght = len(password)
while lenght < 6:
password = input('invalid , so type again : ')
if len(password)>6:
break
while not any(ele.isnumeric() for ele in password):
password = input('invalid , so type again : ')
while not any(ele.isupper() for ele in password):
password = input('invalid , so type again : ')
while not any(ele not in "[@_!#$%^&*()<>?/|}{~:]" for ele in password):
password = input('invalid , so type again : ')
break
答案 6 :(得分:0)
isdigit()
checks the whole string is a digit,如果字符串包含数字,则不会
如果字符串中的所有字符都是数字且至少有一个字符,则返回true,否则返回false。
isupper()
checks the whole string is in uppercase,不是字符串包含至少一个大写字符。
如果字符串中的所有外壳字符都是大写且至少有一个外壳字符,则返回true,否则返回false。
您需要的是使用any
built-in function:
any([x.isdigit() for x in password])
中至少有一位数字,password
将返回True
如果至少有一个字符被视为大写,any([x.isupper() for x in password])
将返回True。答案 7 :(得分:0)
也许你可以使用正则表达式:
class
检查大写字母。
re.search(r"[A-Z]", password)
检查密码中的数字。
答案 8 :(得分:0)
Python 2.7 for循环将为每个字符分配一个条件编号。即列表中的Pa $$ w0rd = 1,2,4,4,2,3,2,2,5。由于集合仅包含唯一值,因此该集合= 1,2,3,4,5;因此,因为所有条件都满足,所以该集合的len =5。如果它是pa $$ w,则该集合将= 2,4,而len = 2,因此无效
name = raw_input("Enter a Password: ")
list_pass=set()
special_char=['#','$','@']
for i in name:
if(i.isupper()):
list_pass.add('1')
elif (i.islower()):
list_pass.add('2')
elif(i.isdigit()) :
list_pass.add('3')
elif(i in special_char):
list_pass.add('4')
if len(name) >=6 and len(name) <=12:
list_pass.add('5')
if len(list_pass) is 5:
print ("Password valid")
else: print("Password invalid")
答案 9 :(得分:0)
''' Minimum length is 5;
- Maximum length is 10;
- Should contain at least one number;
- Should contain at least one special character (such as &, +, @, $, #, %, etc.);
- Should not contain spaces.
'''
import string
def checkPassword(inputStr):
if not len(inputStr):
print("Empty string was entered!")
exit(0)
else:
print("Input:","\"",inputStr,"\"")
if len(inputStr) < 5 or len(inputStr) > 10:
return False
countLetters = 0
countDigits = 0
countSpec = 0
countWS = 0
for i in inputStr:
if i in string.ascii_uppercase or i in string.ascii_lowercase:
countLetters += 1
if i in string.digits:
countDigits += 1
if i in string.punctuation:
countSpec += 1
if i in string.whitespace:
countWS += 1
if not countLetters:
return False
elif not countDigits:
return False
elif not countSpec:
return False
elif countWS:
return False
else:
return True
print("Output: ",checkPassword(input()))
使用正则表达式
s = input("INPUT: ")
print("{}\n{}".format(s, 5 <= len(s) <= 10 and any(l in "0123456789" for l in s) and any(l in "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~" for l in s) and not " " in s))
模块导入
from string import digits, punctuation
def validate_password(p):
if not 5 <= len(p) <= 10:
return False
if not any(c in digits for c in p):
return False
if not any(c in punctuation for c in p):
return False
if ' ' in p:
return False
return True
for p in ('DJjkdklkl', 'John Doe'
, '$kldfjfd9'):
print(p, ': ', ('invalid', 'valid')[validate_password(p)], sep='')
答案 10 :(得分:0)
示例:
import pandas as pd
import numpy as np
data = pd.DataFrame({'A':np.nan,'B':1.096, 'C':1}, index=[0])
print(data)
print(data.dtypes)
for col in data.columns:
data[col].replace(to_replace={np.nan: None}, inplace=True)
print(data)
print(data.dtypes)
答案 11 :(得分:0)
uppercase_letter = ['A', 'B','C', 'D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z']
number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
import re
info ={}
while True:
user_name = input('write your username: ')
if len(user_name) > 15:
print('username is too long(must be less than 16 character)')
elif len(user_name) < 3 :
print('username is short(must be more than 2 character)')
else:
print('your username is', user_name)
break
while True:
password= input('write your password: ')
if len(password) < 8 :
print('password is short(must be more than 7 character)')
elif len(password) > 20:
print('password is too long(must be less than 21 character)')
elif re.search(str(uppercase_letter), password ) is None :
print('Make sure your password has at least one uppercase letter in it')
elif re.search(str(number), password) is None :
print('Make sure your password has at least number in it')
else:
print('your password is', password)
break
info['user name'] = user_name
info['password'] = password
print(info)
答案 12 :(得分:0)
我已经包含了一些额外的功能,以防人们必须判断是否包含任何字母表。但我想如果检查 lower()
和 upper()
可能是多余的。
但我还包含了 string.punctuation
,它可用于识别用户“密码”中的任何特殊字符。
如果输入的长度在 6 到 12 个字符之间,代码也会测量。
import string
def check_password():
str_input = input()
alpha_ = digit_ = lower_ = upper_ = char_ = ""
if len(str_input) >= 6 and len(str_input) <= 12:
for i in range(len(str_input)):
if (str_input[i].isalpha()):
alpha_ = alpha_ + str_input[i]
if (str_input[i].isdigit()):
digit_ = digit_ + str_input[i]
if (str_input[i].islower()):
lower_ = lower_ + str_input[i]
if (str_input[i].isupper()):
upper_ = upper_ + str_input[i]
if (str_input[i] in string.punctuation):
char_ = char_ + str_input[i]
if len(alpha_) >= 1 and len(digit_) >= 1 and len(lower_) >= 1 and len(upper_) >= 1 and len(char_) >= 1 and len(alpha_ + digit_ + char_) >=6 and len (str_input) <= 12:
print("Valid")
else:
print("Invalid")
答案 13 :(得分:-1)
或者你可以用它来检查它是否至少有一位数字:
min(passwd).isdigit()