乐之之

知而行乐,乐而行之,天道酬勤,学无止境。
6、统计字符串中每个字符的次数

题目:

  输入一串字符串,分别统计出每一个符号出现的次数。

str = "hello world i love python"

 

解题思路:

  1、创建一个字典

  2、对str进行遍历

  3、将字符串中的每个字符(键)分别对应次数(值)

 

答案:

str = "hello world i love python"
str1 = {}
for data in str:
    str1[data] = str.count(data)
print(str1)

----------------------------
{'h': 2, 'e': 2, 'l': 4, 'o': 4, ' ': 4, 'w': 1, 'r': 1, 'd': 1, 'i': 1, 'v': 1, 'p': 1, 'y': 1, 't': 1, 'n': 1}

 

posted on 2022-10-20 17:08  乐之之  阅读(78)  评论(0编辑  收藏  举报