美文网首页
Python-怎么用python统计字符串中每个字符出现的次数?

Python-怎么用python统计字符串中每个字符出现的次数?

作者: 催眠_a363 | 来源:发表于2017-11-02 23:22 被阅读0次
def calculate_character_num(s):
    '''This function calculate each character(from A-z) number from str.'''
    # 去除字符串中的空格
    s =list( ''.join(s.split()))
    # 去重
    s1 = set(s)
    # 转换成列
    l = list(s1)
    t ={}

    for a in range(len(l)):
        num = 0
        # reversed()方法的作用是把列表前后置换,这样保证pop()之后,不超出索引。
        # pop()后会改变原字符串,但是for循环的次数是没有改变的。
        for i in reversed(range(len(s))):
            if l[a] == s[i]:
                num = num + 1
                s.pop(i)
        t[l[a]] = str(num)
    return t

if __name__ == '__main__':
    str1 = 'hello world'
    t = calculate_character_num(str1)
    print(t)

相关文章

网友评论

      本文标题:Python-怎么用python统计字符串中每个字符出现的次数?

      本文链接:https://www.haomeiwen.com/subject/ngczpxtx.html