Python程序查找给定字符串中每个字符的出现

在本文中,我们将学习下面给出的问题陈述的解决方案。

问题陈述 -给我们一个字符串,我们需要找到给定字符串中每个字符的出现。

在这里,我们将讨论以下三种方法:L

方法1:蛮力方法

示例

test_str = "Nhooo"
#count dictionary
count_dict = {}
for i in test_str:
   #for existing characters in the dictionary
   if i in count_dict:
      count_dict[i] += 1
   #for new characters to be added
   else:
      count_dict[i] = 1
print ("Count of all characters in Nhooo is :\n "+
str(count_dict))

输出结果

Count of all characters in Nhooo is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}

方法2:使用集合模块

示例

from collections import Counter
test_str = "Nhooo"
# using collections.Counter() we generate a dictionary
res = Counter(test_str)
print ("Count of all characters in Nhooo is :\n "+
str(dict(res)))

输出结果

Count of all characters in Nhooo is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}

方法3:set()在Lambda表达式中使用

示例

test_str = "Nhooo"
# using set() to calculate unique characters in the given string
res = {i : test_str.count(i) for i in set(test_str)}
print ("Count of all characters in Nhooo is :\n "+
str(dict(res)))

输出结果

Count of all characters in Nhooo is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}

结论

在本文中,我们了解了如何找到给定字符串中每个字符的出现。