Search code examples
pythonpasswordsuppercase

Am I able to use the function 'count()' to find the amount of upper cases in a password? (PYTHON)


When I enter the code below, it says:

TypeError: must be str, not list

Does this mean I cannot use the function count() or is there another way I could program it?

password = "CheeseMakesMeHappy"
uppercase =["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
print (password.count(uppercase))

Solution

  • Just go through every character in the password and check if it is an uppercase character. For example:

    password = "FoOoObA"
    print(len([c for c in password if c.isupper()]))
    >> 4
    

    Another method is using sets and bitmasks to count the number of unique uppercase characters.

    password = "CheeseMakesMeHappy"
    uppercase = set(["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"])
    print(len(set(password)&uppercase))
    >> 3
    

    The set solution however will only count UNIQUE characters, but in the case of password strength metering that might not be a bad idea.