HaV*_*ViK 2 python passwords validation
所以我必须创建验证密码是否的代码:
这是代码:
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 capital letter in it")
else:
print("Your password seems fine")
break
validate()
Run Code Online (Sandbox Code Playgroud)
我不确定有什么问题,但是当我输入一个有号码的密码时 - 它一直告诉我我需要一个带有数字的密码.有解决方案吗
您可以将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()
Run Code Online (Sandbox Code Playgroud)
password.isdigit()不检查密码是否包含数字,它根据以下方式检查所有字符:
str.isdigit():如果字符串中所有字符都是数字并且至少有一个字符,则返回 true,否则返回 false。
password.isupper()不检查密码是否包含大写字母,它根据以下规则检查所有字符:
str.isupper():如果字符串中所有大小写字符均为大写且至少有一个大小写字符,则返回 true,否则返回 false。
如需解决方案,请在check if a string contains a number处检查问题和接受的答案。
您可以构建自己的hasNumbers()函数(从链接问题复制):
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
Run Code Online (Sandbox Code Playgroud)
和一个hasUpper()- 函数:
def hasUpper(inputString):
return any(char.isupper() for char in inputString)
Run Code Online (Sandbox Code Playgroud)
小智 5
r_p = re.compile('^(?=\S{6,20}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])')
Run Code Online (Sandbox Code Playgroud)
此代码将验证您的密码: