所以我想跟踪子串的次数" hi"已被用于字符串" kjdhsfhiskdjhi"使用for循环。
到目前为止,这就是我所拥有的。问题是,它只计算字符串中的字母数s = "kjdhsfhiskdjhi"
substring = "hi"
numofhi = 0
for substring in s:
numofhi +=
print('number of times hi occurs is: ' + str(numofhi))
谢谢!
答案 0 :(得分:0)
我认为RomanPerekhrest给出的答案是最简单有效的。
如果你真的需要一个for循环,你可以使用:
s = "kjdhsfhiskdjhi"
substring = "hi"
substring_length = len(substring)
numofhi = 0
for chunk in ["".join(s[x:x+substring_length]) for x in range(0, len(s), substring_length)]:
if chunk == substring:
numofhi += 1
print('number of times hi occurs is: ' + str(numofhi))