Python 程序可查找特定字符串中的每个字符的出现次数
在本文中,我们将了解如何解决下述问题。
问题陈述 − 我们已有一个字符串,我们需要找出特定字符串中每个字符出现的次数。
这里我们将讨论 3 种方法,如下所述:L
方法 1 − 暴力法
示例
test_str = "Tutorialspoint"
#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 Tutorialspoint is :\n "+
str(count_dict))输出
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}方法 2 − 使用 collections 模块
示例
from collections import Counter
test_str = "Tutorialspoint"
# using collections.Counter() we generate a dictionary
res = Counter(test_str)
print ("Count of all characters in Tutorialspoint is :\n "+
str(dict(res)))输出
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}方法 3 − 在 lambda 表达式中使用 set()
示例
test_str = "Tutorialspoint"
# 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 Tutorialspoint is :\n "+
str(dict(res)))输出
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}结论
在本文中,我们已了解如何在特定字符串中找出每个字符出现的次数。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP