我试图计算一个字符在字符串中出现的次数。例如,符号b
在字符串abbcddba
中出现3次。但是,下面的代码计算字符串的长度。例如,如果我尝试计算b
在字符串abbcddba
中出现的次数,它会给出8
的计数。你知道吗
MyStr = input('Please enter a string: ')
symb = input('Which character you want to the count for: ')
count = 0
for i in range(0,len(MyStr)):
if symb in MyStr:
count = count + 1
print(count)
我哪里出错了?你知道吗
注意:这是一个用于查找字符串中子字符串/字符计数的通用解决方案
继续检查你的符号是否出现在Mystr的开头,如果发现,递增计数并去掉Mystr开头的符号,否则跳过第一个字符继续!你知道吗
使用for循环:
我们能这样做吗:
相关问题 更多 >
编程相关推荐