使用print计算一串字符串各字符出现的个数

方法1:

 

方法一:
In [1]: str="dfadDFAfadfefFDs2e3rDFDFDFd3f"


In [2]: print({i:str.count(i) for i in str})
{'d': 4, 'f': 5, 'a': 2, 'D': 5, 'F': 5, 'A': 1, 'e': 2, 's': 1, '2': 1, '3': 2, 'r': 1}


方法二:
In [4]: import collections

In [5]: str="dfadDFAfadfefFDs2e3rDFDFDFd3f"

In [6]: obj = collections.Counter(str)

In [7]: print(obj)
Counter({'f': 5, 'D': 5, 'F': 5, 'd': 4, 'a': 2, 'e': 2, '3': 2, 'A': 1, 's': 1, '2': 1, 'r': 1})

 

 

方法2:

 

posted @ 2022-03-02 15:04  忙碌在路上  阅读(136)  评论(0编辑  收藏  举报