Checking the strength of a password (how to check conditions)

后端 未结 4 660
日久生厌
日久生厌 2020-11-27 20:35

I am trying to create a system that requires you to enter a password. If it is all lower, upper or num then print weak, if it is two of the conditions, then it is med and if

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 21:02

    password.isalnum() returns a boolean, so password.isalnum()==password will always be False.

    Just omit the ==password part:

    if password.lower()== password or password.upper()==password or password.isalnum():
        # ...
    

    Next, it can never be both all upper and lower, or all upper and numbers or all lower and all numbers, so the second condition (medium) is impossible. Perhaps you should look for the presence of some uppercase, lowercase and digits instead?

    However, first another problem to address. You are testing if the password is alphanumeric, consisting of just characters and/or numbers. If you want to test for just numbers, use .isdigit().

    You may want to familiarize yourself with the string methods. There are handy .islower() and .isupper() methods available that you might want to try out, for example:

    >>> 'abc'.islower()
    True
    >>> 'abc123'.islower()
    True
    >>> 'Abc123'.islower()
    False
    >>> 'ABC'.isupper()
    True
    >>> 'ABC123'.isupper()
    True
    >>> 'Abc123'.isupper()
    False
    

    These are faster and less verbose that using password.upper() == password, the following will test the same:

    if password.isupper() or password.islower() or password.isdigit():
        # very weak indeed
    

    Next trick you want to learn is to loop over a string, so you can test individual characters:

    >>> [c.isdigit() for c in 'abc123']
    [False, False, False, True, True, True]
    

    If you combine that with the any() function, you can test if there are some characters that are numbers:

    >>> any(c.isdigit() for c in 'abc123')
    True
    >>> any(c.isdigit() for c in 'abc')
    False
    

    I think you'll find those tricks handy when testing for password strengths.

提交回复
热议问题