繁体   English   中英

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

[英]Count multiple letters in string Python

我正在尝试计算下面字符串中字母的“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为假,则返回其值; 否则,计算y并返回结果值。

换句话说:

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

这里的代码:

import re
name1 = input("What is your name? ")
name2 = input("Whats is their name? ")
c = len(re.findall('[true]', name1 + name2)

如果你有多个字符串。

计算s所有字母:

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

然后对来自s任何键(字母)求和:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM