在 Python 中计算字符串中某个字符的出现次数

pythonserver side programmingprogramming更新于 2026/1/22 12:28:17

给定一个字符串和一个字符。我们想要找出给定字符在给定字符串中重复了多少次。

使用 range 和 len

我们设计了一个 for 循环,将字符与字符串中存在的每个字符进行匹配,这些字符可通过索引访问。range 和 len 函数可帮助我们确定从字符串的左侧移动到右侧时需要进行多少次匹配。

示例

Astr = "How do you do"
char = 'o'
# 给定字符串和字符
print("给定字符串:\n", Astr)
print("给定字符:\n",char)
res = 0
for i in range(len(Astr)):
   # 检查字符串中的字符
   if (Astr[i] == char):
      res = res + 1
print("字符串中出现字符的次数:\n",res)

输出

运行上述代码得到以下结果 −

给定字符串:
How do you do
给定字符:
o
字符串中出现字符的次数:
4

使用 Counter

我们应用 collections 模块中的 Counter 函数来获取字符串中每个字符的计数。然后仅选择索引与我们要搜索的字符的值匹配的计数。

示例

from collections import Counter
Astr = "How do you do"
char = 'o'
# 给定字符串和字符
print("给定字符串:\n", Astr)
print("给定字符:\n",char)
count = Counter(Astr)
print("字符串中出现字符的次数:\n",count['o'])

输出

运行上述代码得到以下结果 −

给定字符串:
How do you do
给定字符:
o
字符串中出现字符的次数:
4

相关文章


有用资源