呃呵呵哈哈啥 2021-03-11 00:59 采纳率: 100%
浏览 49
已采纳

python中,str1是26个字母,str2是一篇英文文章,如何分别得每个字母在str2中的个数?

python当中,有两个字符串,str1是26个字母,str2是一篇英文文章,如何分别得出每个字母在str2中的个数?

for循环可以自动创建多个变量并一一赋值吗?

一个个写太麻烦了……

  • 写回答

1条回答 默认 最新

  • coagenth 2021-03-11 01:58
    关注

    用collections库中Counter,很方便地计算出字母的出现次数:

    from collections import Counter

    import string

    for k,v in Counter('This is a test.'.lower()).items():

        if k!=" " and k not in string.punctuation:

            print(f'{k}出现{v}次')

    输出:

    t出现3次
    h出现1次
    i出现2次
    s出现3次
    a出现1次
    e出现1次

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?