子字符串在字符串中出现多少次而不使用任何计数或其他函数

2024-10-01 11:40:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算一个字符在字符串中出现的次数。例如,符号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)

我哪里出错了?你知道吗


Tags: 字符串代码inforinputcount符号字符
2条回答

注意:这是一个用于查找字符串中子字符串/字符计数的通用解决方案

继续检查你的符号是否出现在Mystr的开头,如果发现,递增计数并去掉Mystr开头的符号,否则跳过第一个字符继续!你知道吗

>>> MyStr = 'thisishelloheyhihello'
>>> symb = 'hello'
>>> count=0
>>> while symb in MyStr:
...     if MyStr.startswith(symbol):
...             count+=1
...             MyStr = MyStr[MyStr.find(synb,2):]
...     else:MyStr=MyStr[1:]
... 
>>> print count
2

使用for循环:

>>> for i in range(len(MyStr)):
...     if MyStr[i:].startswith(symb):
...             count+=1
... 
>>> count
3

我们能这样做吗:

s='abbcddba'
e='b'
c=0
for a in s:
    if e==a:
        c=c+1
print(c)

相关问题 更多 >