Fire HTML5 dragstart

htmlweb developmentfront end technology更新于 2026/1/22 11:56:17

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

使用 range 和 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)

输出

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

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

使用 Counter

我们应用 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

相关文章


有用资源