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')
Output: 5
解决方案
You probably mean s.count('l') + s.count('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