[python] 計算字符串中字符的出現次數



Answers

你可以使用count()

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

計算字符串中字符出現次數的最簡單方法是什麼?

例如,計算'Mary had a little lamb'出現'a'的次數




str = "count a character occurance"

List = list(str)
print (List)
Uniq = set(List)
print (Uniq)

for key in Uniq:
    print (key, str.count(key))



"aabc".count("a")



正則表達式可能?

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



沒有比這個恕我直言,你可以添加上方或下方的方法

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



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



“沒有使用count找到你想要的字符串”方法。

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



這會給你一個字符串中每個字符的出現。 O / P也是字符串格式:

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





Links