【发布时间】:2017-12-17 11:58:06
【问题描述】:
例如,如果我想知道 hello 在这个词中出现的次数:hellohellothere,我的代码会给我2,这是正确的。但是如果我有hellotherehello,我的代码不会给我2,这意味着我认为我的第二个for循环有问题。
我的代码计算字符串中的字母数,然后将其除以字符串的长度,得出字符串实际出现的次数,但我认为这不是问题所在。
这里是代码。
word = input("Enter a word: ")
find = input("Enter string to find")
count = int(0)
for x in range(0, len(word)-len(find)):
if word[x] == find[0]:
for i in range(0, len(find)):
if word[x+i] == find[i]:
count += 1
else: break
count = count/len(find)
print("Number of times it occurs is: ", count)
【问题讨论】:
-
word.count(find)...
标签: python string for-loop if-statement