如何计算字符串中字符出现的次数?

如。“a”在“Mary had a little lamb”中出现了4次。


当前回答

使用数:

sentence = 'A man walked up to a door'
print(sentence.count('a'))
# 4

其他回答

你可以使用.count():

>>> 'Mary had a little lamb'.count('a')
4
spam = 'have a nice day'
var = 'd'


def count(spam, var):
    found = 0
    for key in spam:
        if key == var:
            found += 1
    return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))

你可以使用循环和字典。

def count_letter(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result

使用数:

sentence = 'A man walked up to a door'
print(sentence.count('a'))
# 4

这是公认答案的延伸,你应该在文本中寻找所有字符的计数。

# Objective: we will only count for non-empty characters

text = "count a character occurrence"
unique_letters = set(text)
result = dict((x, text.count(x)) for x in unique_letters if x.strip())

print(result)
# {'a': 3, 'c': 6, 'e': 3, 'u': 2, 'n': 2, 't': 2, 'r': 3, 'h': 1, 'o': 2}