我在python上编写密码强度代码,我试图找出我的密码(p
)是否包含一个数字,我已经找到了如何查看它是否包含大写和小写字母p.isupper()
或p.islower()
。我也把它们放在一起了。我的朋友告诉我如何查看密码是否仅包含数字,但我现在需要你的帮助。
running=True
while running:
p=raw_input("What is your Password? ")
if len(p) <6:
print "Your Password is too short"
if len(p) >12:
print "Your Password is too long"
if len(p) == 6 or 7 or 8 or 9 or 10 or 11 or 12:
print "Password Length OK"
running=False
print "Loop Broken" #this will be deleted, only for my help now
if p.isupper():
print "Your Password is weak as it only contains capital letters"
if p.islower():
print "Your Password is weak as it only contains lower case letters"
if p.isupper and p.islower:
print "Your Password is of medium strength, try adding some numbers"
try:
int(p)
print "Your Password is weak as it only contains numbers"
except (ValueError, TypeError):
pass
如果密码包含大写或小写字母和数字,我现在需要的是代码。
答案 0 :(得分:6)
对我来说,正则表达式绝对是解决这个问题的最简单方法。
给定一个示例密码password
,您检查它的方式是:
import re
# Check if contains at least one digit
if re.search(r'\d', password):
print "Has a digit"
# Check if contains at least one uppercase letter
if re.search(r'[A-Z]', password):
print "Has uppercase letter"
# Check if contains at least one lowercase letter
if re.search(r'[a-z]', password):
print "Has lowercase letter"
对于其他部分,您可以继续使用.isupper()
和.islower()
。
顺便说一下,这部分代码:
if p.isupper and p.islower:
print "Your Password is of medium strength, try adding some numbers"
无法按照您的意愿运作。首先,你实际上没有调用方法,因为你没有放括号 - 你需要写if p.isupper() and p.islower():
。其次,这实际上并不是你想要的。您正在尝试检查它是否包含两个小写和大写数字。相反,你要检查它是完全大写的和完全小写,显然它不能同时是两者,所以if语句将始终返回False
。相反,你会想要使用类似的东西:
if re.search(r'[a-z]', password) and re.search(r'[A-Z]', password):
或者,没有re
:
import string
if any(letter in string.ascii_lowercase for letter in password) and \
any(letter in string.ascii_uppercase for letter in password):
或者:
if any(letter.islower() for letter in password) and \
any(letter.isupper() for letter in password):
我碰巧更喜欢re
,因为它更简洁。
答案 1 :(得分:1)
我想你要检查你的密码是否包含所有这些:小写,大写和数字。
>>> from string import ascii_lowercase, ascii_uppercase, digits
>>> s_lc = set(ascii_lowercase)
>>> s_uc = set(ascii_uppercase)
>>> s_d = set(digits)
def func(strs):
s = set(strs)
return all(s & x for x in (s_lc,s_uc,s_d ))
...
>>> func('fooBar09')
True
>>> func('fooBar')
False
>>> func('900')
False
>>> func('900aB')
True
其次len (p) == 6 or 7 or 8 or 9 or 10 or 11 or 12
将被评估为:
(len(p) == 6) or 7
因此,如果len(p)
为6,那么它会返回True
其他7(这也是Truthy值)
应该是:if 6 <= len(p) <= 12
>>> 7 or 8 or 9 or 10 or 11 or 12
7
使用while True
代替使用标记变量,您需要if-elif-else
条件而不是if-if
:
while True:
p=raw_input("What is your Password? ")
le = len(p)
if le <6:
print "Your Password is too short"
elif le >12:
print "Your Password is too long"
elif 6 <= le <= 12:
print "Password Length OK"
break