在字符串Python中计数多个字母

2024-04-23 22:37:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在数下面字符串中的字母“l”和“o”。 如果我数一个字母,这似乎是可行的,但只要我数下一个字母‘o’,字符串就不会加到总数中。我错过了什么?

s = "hello world"

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

Output: 5


Tags: and字符串helloworldoutputcount字母print
3条回答

你可能是指s.count('l') + s.count('o')

您粘贴的代码等于s.count('o')and运算符检查其第一个操作数(在本例中为l)是否为false。如果为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

Official documentation

或者,由于要计算给定字符串中多个字母的外观,请使用^{}

>>> from collections import Counter
>>>
>>> s = "hello world"
>>> c = Counter(s)
>>> c["l"] + c["o"]
5

请注意,当前使用would evaluate作为s.count('o')s.count('l' and 'o')

The expression x and y first evaluates x: if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

换句话说:

>>> 'l' and 'o'
'o'

使用正则表达式:

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

map

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

相关问题 更多 >