如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
你可以使用.count():
>>> 'Mary had a little lamb'.count('a')
4
其他回答
Python 3
有两种方法可以做到这一点:
1)内置函数count()
sentence = 'Mary had a little lamb'
print(sentence.count('a'))`
2)不使用函数
sentence = 'Mary had a little lamb'
count = 0
for i in sentence:
if i == "a":
count = count + 1
print(count)
myString.count('a');
更多信息请点击这里
要获得所有字母的计数,请使用集合。计数器:
>>> from collections import Counter
>>> counter = Counter("Mary had a little lamb")
>>> counter['a']
4
不使用Counter(), count和regex获得所有字符计数的另一种方法
counts_dict = {}
for c in list(sentence):
if c not in counts_dict:
counts_dict[c] = 0
counts_dict[c] += 1
for key, value in counts_dict.items():
print(key, value)
最简单的方法是一行代码:
'Mary had a little lamb'.count("a")
但是如果你想用这个也可以:
sentence ='Mary had a little lamb'
count=0;
for letter in sentence :
if letter=="a":
count+=1
print (count)