2016-05-10 181 views
0

不,我不是在标题中诅咒。我需要创建一个密码处理程序来检查输入是否符合某些条件,其中之一是它必须包含字符$ @!%& * _中的一个。 这是我目前有。

def pword(): 
    global password 
    global lower 
    global upper 
    global integer 

password = input("Please enter your password ") 
length = len(password) 
lower = sum([int(c.islower()) for c in password]) 
upper = sum([int(c.isupper()) for c in password]) 
integer = sum([int(c.isdigit()) for c in password]) 


def length(): 
    global password 
if len(password) < 8: 
    print("Your password is too short, please try again") 
elif len(password) > 24: 
    print("Your password is too long, please try again") 

def strength(): 
    global lower 
    global upper 
    global integer 
if (lower) < 2: 
    print("Please use a mixed case password with lower case letters") 
elif (upper) < 2: 
    print("Please use a mixed case password with UPPER case letters") 
elif (integer) < 2: 
    print("Please try adding numbers") 
else: 
    print("Strength Assessed - Your password is ok") 
+0

你可以用're.match(...)'标准库的're'模块中。请注意,您所匹配的某些符号在正则表达式的上下文中具有不同的含义,因此请务必将它们转义 - 例如在匹配中使用''\ *''来查找文字'*'和''*''表示“0或更多次重复”。 https://docs.python.org/3.5/library/re.html#match-objects –

+0

顺便说一下,除非你修改它们,否则你不需要为函数内部的变量声明'全局foo' - 它们[范围分辨率规则]已经具有对全球的阅读权限(http://stackoverflow.com/a/292502/149428)。你可以在'length()'和'strength()'中删除所有的全局装饰。 –

回答

0

这种事情会工作:

required='[email protected]!%&*_' 

def has_required(input): 
    for char in required: 
     if input.contains(char): 
      return True 
    return False 

has_required('Foo') 
0
must_have = '[email protected]!%&*_' 
if not any(c in must_have for c in password): 
    print("Please try adding %s." % must_have) 

any(c in must_have for c in password)将返回True如果password中的任何一个字符也是must_have,换句话说,它将返回True时,密码是好的。因为想要测试不好的密码,我们在其前面放置了not以反转测试。因此,print语句仅在此处针对错误密码执行。

+1

谢谢,这工作 – vilty

0

您可以使用列表理解+内置的any()轻松实现此功能。

has_symbol = any([symbol in password for symbol in list('[email protected]!%&*_')]) 

或者多一点打散:

required_symbols = list('[email protected]!%&*_') 
has_symbol = any([symbol in password for symbol in required_symbols])