简体   繁体   中英

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))

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.

The problem is that the method count() expects a string object. Right now, with this line (password.count(uppercase)) , you are effectively passing an Array object to your function. See zeraien's answer for a good solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM