计算字符串Python中的多个字母 [英] Count multiple letters in string Python
本文介绍了计算字符串Python中的多个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在下面的字符串中计算字母的 l和 o。
如果我计算一个字母似乎可行,但是一旦我计算下一个字母 o,该字符串就不会添加到总数中。我想念什么?
I'm trying to count the letter's 'l' and 'o' in the string below. It seems to work if i count one letter, but as soon as i count the next letter 'o' the string does not add to the total count. What am I missing?
s = "hello world"
print s.count('l' and 'o')
输出:5
Output: 5
推荐答案
您可能是指 s.count('l')+ s.count( 'o')
。
您粘贴的代码等于 s.count('o')
:和
运算符检查其第一个操作数(在这种情况下为 l
)是否为假。如果为false,则返回其第一个操作数( l
),但不是,因此返回第二个操作数( o $
The code you've pasted is equal to s.count('o')
: the and
operator checks if its first operand (in this case l
) is false. If it is false, it returns its first operand (l
), but it isn't, so it returns the second operand (o
).
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> True and 'x'
'x'
>>> False and 'x'
False
>>> 'x' and True
True
>>> 'x' and False
False
>>> 'x' and 'y'
'y'
>>> 'l' and 'o'
'o'
>>> s.count('l' and 'o')
2
>>> s.count('o')
2
>>> s.count('l') + s.count('o')
5
这篇关于计算字符串Python中的多个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文