4

我正在 python 上编写密码强度代码,我试图找出我的密码 ( p) 是否包含一个数字,我已经找到了如何查看它是否包含大写和小写字母p.isupper()or 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

我现在需要的只是密码,如果密码包含小写或大写字母和数字。

4

2 回答 2

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,因为它更简洁。

于 2013-06-14T12:58:18.727 回答
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 那么它返回Trueelse 7(这也是一个真值)

它应该是 :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
于 2013-06-14T10:10:47.340 回答