如何检查字符串是否符合某些要求

时间:2013-12-17 10:49:47

标签: python

如何检查字符串以查看它是否包含大写和小写以及符号?我还没能找到我在网上理解的答案,任何帮助都会非常感激。

代码:

def final_output():
    print("worthless")

def re_main():
    main()

def password_checker(password):
    strength = 0
    letters = isalpha()
    numbers = isdigit()

    if letters and numbers == 'False':
        print("works")


def main():
    password = (input("Please input password:"))
    passwordChecker = (input("Please re-enter your password:"))

    if password != passwordChecker:
        print("Passwords did not match, please try again.")
        re_main()
    else:
        password_checker(password)


main()

3 个答案:

答案 0 :(得分:1)

您需要检查.isupper(),is_lower()和isdigit()的密码字符串的每个元素

passwd = "Password123"
is_upper = any(i.isupper() for i in passwd)
is_lower = any(i.islower() for i in passwd)
is_digit = any(i.isdigit() for i in passwd)

此处“any”表示该字符的至少1符合条件(在这种情况下为Upper,lower和digit)

答案 1 :(得分:0)

string模块中有几个字符串(标准Python库的一部分)可以在这里使用:

>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.digits
'0123456789'

然后,您可以检查密码中的任何字符是否在这些字符串中,如下所示(我还包括长度检查):

def check_pass(pwd, min_length=8, lower=True, upper=True, punc=True, num=True):
    if len(pwd) < min_length:
        return False
    if lower and not any(char in string.ascii_lowercase for char in pwd):
        return False
    if upper and not any(char in string.ascii_uppercase for char in pwd):
        return False
    if punc and not any(char in string.punctuation for char in pwd):
        return False
    if num and not any(char in string.digits for char in pwd):
        return False
    return True

答案 2 :(得分:0)

这可能会很好......

<强>代码:

import string
s = 'Password#123'

if any(i for i in s if i in string.ascii_uppercase) \
and any(i for i in s if i in string.ascii_lowercase) \
and any(i for i in s if i in string.punctuation): print 'yes'

<强>输出:

yes

希望这会有所帮助.. :)