统计字符串中某个字符的出现次数(Python)


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

使用范围和 len

我们设计了一个 for 循环来匹配字符串中存在的每个字符,这些字符使用索引访问。range 和 len 函数帮助我们确定从字符串的左向右移动时需要完成匹配的次数。

示例

 实时演示

Astr = "How do you do"
char = 'o'
# Given String and Character
print("Given String:\n", Astr)
print("Given Character:\n",char)
res = 0
for i in range(len(Astr)):
   # Checking character in string
   if (Astr[i] == char):
      res = res + 1
print("Number of time character is present in string:\n",res)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

运行以上代码时,我们得到以下结果 -

Given String:
How do you do
Given Character:
o
Number of time character is present in string:
4

使用计数器

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

示例

 实时演示

from collections import Counter
Astr = "How do you do"
char = 'o'
# Given String and Character
print("Given String:\n", Astr)
print("Given Character:\n",char)
count = Counter(Astr)
print("Number of time character is present in string:\n",count['o'])

输出

运行以上代码时,我们得到以下结果 -

Given String:
How do you do
Given Character:
o
Number of time character is present in string:
4

更新于: 2020 年 6 月 4 日

670 次观看

开启你的 职业生涯

完成课程获得认证

开始吧
广告