计算字符串中的多个字母 Python
Count multiple letters in string Python
我正在尝试计算下面字符串中字母的 'l' 和 'o'。
如果我数一个字母似乎可行,但是一旦我数下一个字母 'o' ,该字符串就不会添加到总数中。我错过了什么?
s = "hello world"
print s.count('l' and 'o')
Output: 5
你的意思可能是 s.count('l') + s.count('o')
。
您粘贴的代码等于 s.count('o')
:and
运算符检查其第一个操作数(在本例中为 l
)是否为假。如果它是 false,它 returns 它的第一个操作数 (l
),但它不是,所以它 returns 第二个操作数 (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
或者,由于您要计算给定字符串中多个字母的出现次数,请使用 collections.Counter
:
>>> from collections import Counter
>>>
>>> s = "hello world"
>>> c = Counter(s)
>>> c["l"] + c["o"]
5
请注意 s.count('l' and 'o')
您当前正在使用 would evaluate 作为 s.count('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
计算 s
中的所有字母:
answer = {i: s.count(i) for i in s}
然后对 s
:
中的任何键(字母)求和
print(answer['l'] + answer['o'])
我正在尝试计算下面字符串中字母的 'l' 和 'o'。 如果我数一个字母似乎可行,但是一旦我数下一个字母 'o' ,该字符串就不会添加到总数中。我错过了什么?
s = "hello world"
print s.count('l' and 'o')
Output: 5
你的意思可能是 s.count('l') + s.count('o')
。
您粘贴的代码等于 s.count('o')
:and
运算符检查其第一个操作数(在本例中为 l
)是否为假。如果它是 false,它 returns 它的第一个操作数 (l
),但它不是,所以它 returns 第二个操作数 (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
或者,由于您要计算给定字符串中多个字母的出现次数,请使用 collections.Counter
:
>>> from collections import Counter
>>>
>>> s = "hello world"
>>> c = Counter(s)
>>> c["l"] + c["o"]
5
请注意 s.count('l' and 'o')
您当前正在使用 would evaluate 作为 s.count('o')
:
The expression
x and y
first evaluatesx
: ifx
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
计算 s
中的所有字母:
answer = {i: s.count(i) for i in s}
然后对 s
:
print(answer['l'] + answer['o'])