# 计算string中字符的出现次数

### 15 Solutions collect form web for “计算string中字符的出现次数”

str.count（sub [，start [，end]]）

`[start, end]`范围内返回子串`sub`的非重叠次数。 可选参数`start``end`被解释为切片符号。

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

` `>>> 'Mary had a little lamb'.count('a') 4` `

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

` `import re my_string = "Mary had a little lamb" len(re.findall("a", my_string))` `
` `myString.count('a');` `

` `"aabc".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))` `

` `a = 'have a nice day' symbol = 'abcdefghijklmnopqrstuvwxyz' for key in symbol: print key, a.count(key)` `

# “不用数字找string”方法。

` `import re def count(s, ch): pass def main(): s = raw_input ("Enter strings what you like, for example, 'welcome': ") ch = raw_input ("Enter you want count characters, but best result to find one character: " ) print ( len (re.findall ( ch, s ) ) ) main()` `

`str.count(a)`是计算string中单个字符的最佳解决scheme。 但是如果你需要计算多于一个的字符，那么你需要多次读取string。

` `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` `
` `str = "count a character occurance" List = list(str) print (List) Uniq = set(List) print (Uniq) for key in Uniq: print (key, str.count(key))` `
` `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_in_str(string,letter): return string.count(letter)` `

` `def count_char(string1): string2="" lst=[] lst1=[] for i in string1: count=0 if i not in lst: for j in string1: if i==j: count+=1 lst1.append(i) lst1.append(count) lst.append(i) string2=''.join(str(x) for x in lst1) return string2 print count_char("aabbacddaabbdsrchhdsdg")` `

`count`绝对是计算string中字符出现的最简洁高效的方法，但是我试图用`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` `

• 如何在PHP中将两个string结合在一起？
• 如何删除java中的所有空格
• 在Java中转换为大写和小写
• PHP - 迭代string字符
• 如何在循环中使用sscanf？
• 去掉MySQL中列的最后两个字符
• std :: string是如何实现的？
• 我怎样才能格式化一个string数字在Android编辑字段中有逗号
• 如何在JavaScript中查找另一个string的所有出现的索引？
• 为什么这个string的长度比它里面的字符长呢？
• T-SQL中的IndexOf函数