【发布时间】:2020-10-20 13:51:21
【问题描述】:
我正在尝试编写一个代码 sn-p,请求用户输入一个字符串 s,然后输入一个子字符串 ss。然后程序必须计算ss 在s 中出现的次数。例如,如果用户输入s = ‘azcbobobegghakl’ 和ss = ‘bob’,那么程序应该打印: Number
bob 出现的次数是:2.
到目前为止,这是我的代码:
def count(s,ss):
Occurrence = 0
if ss in s :
for ss in s :
Occurrence += 1
return Occurrence
#Main program :
s = str(input("Choose a string: "))
ss = str(input("Choose a substring:"))
print ("Number of times " + str(ss) + " occurs is : " + str(count(s,ss)) )
我想要的输出是这样的:
Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 2
但是我得到了这个:
Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 8
那么有人可以帮我修改此代码以提供所需的输出吗?提前致谢
【问题讨论】: