【问题标题】:Password validation - at least one capital, one lower case and one number [duplicate]密码验证 - 至少一个大写,一个小写和一个数字[重复]
【发布时间】:2018-01-23 12:10:08
【问题描述】:

我将如何验证输入以检查它是否包含至少 1 个数字、一个大写字母和一个小写字母。我已经查看了类似的问题,但它们似乎并不是我所需要的,例如只检查数字并拒绝字母,除了具有多个数字、大写字母和小写字母的任何内容之外,我需要它。

【问题讨论】:

标签: python python-3.x validation


【解决方案1】:

您可以像这样使用assert 结合any()string 内置模块:

import string

password = '1Aa'

try:
    assert any(i in string.ascii_lowercase for i in password)
    assert any(i in string.ascii_uppercase for i in password)
    assert any(i in string.digits for i in password)
except AssertionError as e:
    raise Exception('Invalid password!')

【讨论】:

    【解决方案2】:
    import re
    def passwordagain():
    password()
    
    def password():
            print()
            password = input("Enter a secure password: ")
            if   re.search('[A-Z]',password) is None:
                print("Password must contain at least one capital letter and one number.")
                passwordagain() 
            elif re.search('[0-9]',password) is None:
                print("Password must contain at least one capital letter and one number.")
                passwordagain() 
            elif re.search('[a-z]',password) is None: 
                print("Password must contain at least one capital letter and one number.")
                passwordagain()          
            else:
                filename = ("password.");
                with open (filename, "w") as f:
                    f.write (password)
                print()
                print("Password saved")
    

    【讨论】:

    • 什么是passwordagain()
    • 抱歉漏掉了,这只是函数循环的一种方式
    • 这不是一个非常明智的启动无限循环的方法。您应该研究使用 while True: - this question and answer 可能会有所帮助
    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2010-12-07
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多