如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
使用数:
sentence = 'A man walked up to a door'
print(sentence.count('a'))
# 4
其他回答
使用数:
sentence = 'A man walked up to a door'
print(sentence.count('a'))
# 4
不超过这个IMHO -你可以添加上或下的方法
def count_letter_in_str(string,letter):
return string.count(letter)
正则表达式?
import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
myString.count('a');
更多信息请点击这里
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)