Python:统计字符串中各元素出现的次数

统计String中每个单词出现的个数(不区分大小写)
输入描述:输入一个字符串,例如:“a b A v”
输出描述:
v:1
:3
b:1
a:2

def countEach(strs) :
    dic = {}
    strs = strs.lower()
    lens = len(strs)
    i = 0
    while i < lens :
        if strs[i] in dic.keys() :
            dic[strs[i]] += 1
        else :
            dic[strs[i]] = 1
        i += 1
    return dic

def print_result(strs):
    dic = countEach(strs)
    for each in dic.items():
        print(each[0]+':'+str(each[1]))

if __name__ == '__main__' :
    strs = 'a b A v'
    print_result(strs)
    countEach(strs)

结果在这里插入图片描述

你可能感兴趣的:(Python,秋招笔试)