计算字符串Python中的多个字母

问题描述 投票:0回答:5

我正在尝试计算下面字符串中字母“l”和“o”的数量。 如果我数一个字母,它似乎可以工作,但是一旦我数下一个字母“o”,该字符串就不会添加到总数中。我错过了什么?

s = "hello world"

print s.count('l' and 'o')

输出:5

python string count
5个回答
11
投票

您的意思可能是

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

官方文档


7
投票

使用正则表达式:

>>> import re
>>> len(re.findall('[lo]', "hello world"))
5

map
:

>>> sum(map(s.count, ['l','o']))
5

2
投票

或者,由于您要计算给定字符串中多个字母的出现次数,请使用

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'
    

0
投票
计算

s

中的所有字母:

answer = {i: s.count(i) for i in s}
然后将 

s

 中的所有键(字母)相加:

print(answer['l'] + answer['o'])
    

0
投票
s = "hello world" sum([s.count(x) for x in ['l','o']])
输出:5

© www.soinside.com 2019 - 2024. All rights reserved.