2024-04-23 22:37:26 发布
网友
我在数下面字符串中的字母“l”和“o”。 如果我数一个字母,这似乎是可行的,但只要我数下一个字母‘o’,字符串就不会加到总数中。我错过了什么?
s = "hello world" print s.count('l' and 'o')
Output: 5
你可能是指s.count('l') + s.count('o')。
s.count('l') + s.count('o')
您粘贴的代码等于s.count('o'):and运算符检查其第一个操作数(在本例中为l)是否为false。如果为false,则返回第一个操作数(l),但不是,因此返回第二个操作数(o)。
s.count('o')
and
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'):
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.
x and y
x
y
换句话说:
>>> 'l' and 'o' 'o'
使用正则表达式:
>>> import re >>> len(re.findall('[lo]', "hello world")) 5
或map:
map
>>> sum(map(s.count, ['l','o'])) 5
你可能是指
s.count('l') + s.count('o')
。您粘贴的代码等于
s.count('o')
:and
运算符检查其第一个操作数(在本例中为l
)是否为false。如果为false,则返回第一个操作数(l
),但不是,因此返回第二个操作数(o
)。Official documentation
或者,由于要计算给定字符串中多个字母的外观,请使用^{} :
请注意,当前使用would evaluate作为
s.count('o')
的s.count('l' and 'o')
:换句话说:
使用正则表达式:
或
map
:相关问题 更多 >
编程相关推荐