在Python中验证用户输入的字符串的内容?

时间:2016-05-20 05:25:48

标签: python

作为作业的一部分,我创建了一个程序,要求用户输入用户名和密码。

我已完成用户名部分(简单),但在分配说明中,密码必须:

  • 包含大写字符
  • 包含小写字符
  • 超过6个字符
  • 包含数字
  • 没有空格

如果这些条件中的任何一个不正确,则需要显示5条特定的错误消息。

我目前有一些奇怪的行为,错误只出现在特定的顺序中(例如,密码" f"将出现错误"必须有一个大写字符"而不是"必须长于6个字符")。我知道这是因为if语句的嵌套顺序,但是如果有更好的方法......它也出于某种原因没有在密码中捕获空格。我知道它可能不是最有效的方式,但这是我迄今为止所做的:

def validatePassword():
    accept = "n"
    while accept == "n":
        password = input("Please enter a valid password: ")
        upper = "n"
        lower = "n"
        digit = "n"
        length = "n"
        white = "n"
        if len(password) >= 6:
            length = "y"
        for char in password:
            if char in string.ascii_uppercase:
                upper = "y"
            if char in string.ascii_lowercase:
                lower = "y"
            if char in string.digits:
                digit = "y"
            if char not in string.whitespace:
                white = "y"
        if upper == "y":
            if lower == "y":
                if digit == "y":
                    if length == "y":
                        if white == "y":
                            accept = "y"
                        else:
                            print("::: ERROR :::",password,"must not have any white space character.")
                    else:
                        print("::: ERROR :::",password,"must be longer than 6 characters.")
                else:
                    print("::: ERROR :::",password,"must contain a number.")
            else:
                print("::: ERROR :::",password,"must contain a lowercase character.")
        else:
            print("::: ERROR :::",password,"must contain an uppercase character.")

    return password

4 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def validatePassword(password):
    if not any(x.isupper() for x in password):
        return False, "No upper case character"

    if not any(x.islower() for x in password):
        return False, "No lower case character"

    if len(password) < 6:
        return False, "Not longer than 6 characters"

    if not any(x.isdigit() for x in password):
        return False, "No number"

    if any(x.isspace() for x in password):
        return False, "Contains hitespace"

    return True, ""


def test():
    # test some passwords
    test_passwords = ["lkjasdf", "KAJSDF", "lfSF", "asdfADSF", "asdf ADSF 123", "asdfADSF123"]
    for p in test_passwords:
        print validatePassword(p)

    # "real" usage
    while True:
        password = input("Please enter a valid password: ")
        result, message = validatePassword(password)
        if result is True:
            break
        else:
            print(message)

if __name__ == '__main__':
    test()

答案 1 :(得分:0)

显然,执行此操作的正确方法是使用any()和生成器表达式,但看看如何说I'm like 8 weeks into a 10 week introductory course那些可能对您没有帮助。

这里是如何通过循环检查某些类型字符是否存在的字符而不使用任何()来实现的。

def validate_password(password):
    hasUpper = hasLower = hasNumber = hasWhiteSpace = False

    for char in passwordStr:
        if char.isupper():
            hasUpper = True
        if char.islower():
            hasLower = True
        if char.isdigit():
            hasNumber = True
        if char.isspace():
            hasWhiteSpace = True

    if len(password) <= 6:
        return False, "Password must be longer than 6 characters"
    if not hasUpper:
        return False, "Password must contain atleast one uppercase character"
    if not hasLower:
        return False, "Password must contain atleast one lowercase letter"
    if not hasNumber:
        return False, "Password must contain alteast one number"
    if hasWhiteSpace:
        return False, "Password cannot contain any white space"

    return True

答案 2 :(得分:0)

首先,数据类型bool可以代表值TrueFalse。您应该使用它们来表示简单的true / false状态,而不是分配字符串"y""n"

其次,分别检查每个字符并存储是否至少满足一次不同的条件是可能的方法。但是,Python具有强大的字符串检查方法,可以让您的生活更轻松。让我通过编写一个以密码作为参数的简短函数来演示它们,只需返回TrueFalse,具体取决于密码是否符合您的限制:

def is_password_valid(password):

    # check password length:
    if len(password) < 6:
        print("Your password is too short, at least 6 characters are required!")
        return False

    # check if password contains any non-alphanumeric letters (including whitespace):
    # (isalnum() only returns true if the string only contains letters and digits, nothing else)
    if not password.isalnum():
        print("Your password may only contain letters and digits!")
        return False

    # check if password contains letters:
    # (isdigit() only returns true if all of the characters are numbers)
    if password.isdigit():
        print("Your password does not contain any letters!")
        return False

    # check if password contains uppercase letters:
    # (islower() only returns true if all of the letters are lowercase, non-letters are ignored)
    if password.islower():
        print("Your password does not contain any uppercase letters!")
        return False

    # check if password contains lowercase letters:
    # (isupper() only returns true if all of the letters are uppercase, non-letters are ignored)
    if password.isupper():
        print("Your password does not contain any lowercase letters!")
        return False

    # check if password contains lowercase numbers:
    # (isalpha() only returns true if all of the characters are letters)
    if password.isalpha():
        print("Your password does not contain any numbers!")

    # if all conditions above are okay, the password is valid:
    print("The password is okay.")
    return True

您当然可以按照自己的意愿重新排列上面代码中的块。

然后你可以在循环中使用这个辅助函数,现在看起来更简单,更清洁:

def validate_password():
    accept = False
    while not accept:
        password = input("Please enter a valid password: ")
        accept = is_password_valid(password)

答案 3 :(得分:0)

您可以尝试使用正则表达式。如果您不了解正则表达式,正如您在评论中提到的那样,this是一个很棒的网站。

要进行验证,请检查密码是否与使其无效的任何规则匹配,如果不匹配,则为有效密码。

import re
def validate(passwd):
  pattern = r'^(.{0,5}|[^0-9]*|[^A-Z]*|[^a-z]*|.*\s+.*)$'
  result = re.search(pattern, passwd)
  if result:
    print 'Invalid Password'
  else:
    print 'Valid Password'  

这样做是检查passwd是否小于6个字符或不包含数字或不包含大写字符或不包含小写字符或包含空格。如果没有条件匹配,则密码有效。