计算Python中字符串中字符的出现次数
给我们一个字符串和一个字符。我们想找出给定字符在给定字符串中重复多少次。
随着范围和镜头
我们设计了一个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
带柜台
我们从collections模块应用Counter函数来获取字符串中每个字符的计数。然后仅选择索引与我们要搜索的字符值匹配的那些计数。
示例
from collections import CounterAstr = "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
以上是 计算Python中字符串中字符的出现次数 的全部内容, 来源链接: utcz.com/z/343328.html