我正在尝试计算下面字符串中字母“l”和“o”的数量。 如果我数一个字母,它似乎可以工作,但是一旦我数下一个字母“o”,该字符串就不会添加到总数中。我错过了什么?
s = "hello world"
print s.count('l' and 'o')
输出:5
您的意思可能是
s.count('l') + s.count('o')
。
您粘贴的代码等于
s.count('o')
:and
运算符检查其第一个操作数(在本例中为l
)是否为假。如果为 false,则返回第一个操作数 (l
),但事实并非如此,因此返回第二个操作数 (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
使用正则表达式:
>>> import re
>>> len(re.findall('[lo]', "hello world"))
5
或
map
:
>>> sum(map(s.count, ['l','o']))
5
collections.Counter
:
>>> from collections import Counter
>>>
>>> s = "hello world"
>>> c = Counter(s)
>>> c["l"] + c["o"]
5
请注意,您当前使用的
s.count('l' and 'o')
会将 评估为 s.count('o')
:
表达式换句话说:
x and y
首先计算x
:如果x
为 false,则其值为 返回;否则,计算y
,结果值为 回来了。
>>> 'l' and 'o'
'o'
s
中的所有字母:
answer = {i: s.count(i) for i in s}
然后将 s
中的所有键(字母)相加:
print(answer['l'] + answer['o'])
s = "hello world"
sum([s.count(x) for x in ['l','o']])
输出:5