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

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


当前回答

“不使用计数查找字符串中需要的字符”方法。

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()

其他回答

我不知道“最简单的”,但简单的理解可以做到:

>>> my_string = "Mary had a little lamb"
>>> sum(char == 'a' for char in my_string)
4

利用内置的和,生成器理解和bool是整数的子类的事实:如何乘字符等于'a'。

使用数:

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

正则表达式?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))

不超过这个IMHO -你可以添加上或下的方法

def count_letter_in_str(string,letter):
    return string.count(letter)

最简单的方法是一行代码:

'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)