简体   繁体   English

我可以使用函数 'count()' 来查找密码中的大写字母数量吗? (蟒蛇)

[英]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类型错误:必须是 str,而不是列表

Does this mean I cannot use the function count() or is there another way I could program it?这是否意味着我不能使用函数 count() 或者还有其他方法可以对其进行编程吗?

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.然而, set解决方案只会计算 UNIQUE 字符,但在密码强度计量的情况下,这可能不是一个坏主意。

The problem is that the method count() expects a string object.问题在于方法count()需要一个字符串对象。 Right now, with this line (password.count(uppercase)) , you are effectively passing an Array object to your function.现在,通过这一行(password.count(uppercase)) ,您可以有效地将 Array 对象传递给您的函数。 See zeraien's answer for a good solution.请参阅 zeraien 的答案以获得一个好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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