python找出字符串中每個字母出現的次數

#完全用列表方式實現
#!/usr/bin/env python
# coding=utf-8
str1 = "abcdefabcdefgghj"
listStr = []

for eachStr in str1:
    countStr = str1.count(eachStr)
    numStr = eachStr + ":" + str(countStr)
    if numStr not in listStr :
        listStr.append(numStr)

for i in listStr:
    print i
    
    
############用字典方式實現################
#!/usr/bin/python
# coding=utf-8
d = {}

for s in ['c','c','c++','python','python','python','js']:
    if s in d:
        d[s] = d[s] + 1
    else:
        d[s] = 1

for key in d:
    print('%s count is %d')%(key,d[key])


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章