# python count用法 - 計算字符串中字符的出現次數

``````>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
``````
str string

``````from collections import Counter
str = "Mary had a little lamb"
counter = Counter(str)
print counter['a']
``````

``````myString.count('a');
``````

``````my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))
``````

`str.count(a)`是計算字符串中單個字符的最佳解決方案。 但是如果你需要計算比一個更多的字符，那麼你必須多次讀取字符串作為你想要計數的字符。

``````from collections import defaultdict

string = 'Mary had a little lamb'
chars = defaultdict(int)

for char in string:
chars[char] += 1
``````

``````>>>chars['a']
4
>>>chars['x']
0
``````

`count`絕對是計算字符串中字符出現的最簡潔高效的方式，但我嘗試用`lambda`來解決問題，如下所示：

``````sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
``````

``````4
``````

``````sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
``````

``````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 check_freq(str):
freq = {}
for c in str:
freq[c] = str.count(c)
return freq

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}
``````

### Tags

python   string   count