以下代码显示“单词”在字符串中出现一次的位置。如何更改代码,以便如果“单词”在字符串中出现多次,它将打印所有位置?
string = input("Please input a sentence: ")
word = input("Please input a word: ")
string.lower()
word.lower()
list1 = string.split(' ')
position = list1.index(word)
location = (position+1)
print("You're word, {0}, is in position {1}".format (word, location))
sentence = input("Please input a sentence: ")
word = input("Please input a word: ")
sentence = sentence.lower()
word = word.lower()
wordlist = sentence.split(' ')
print ("Your word '%s' is in these positions:" % word)
for position,w in enumerate(wordlist):
if w == word:
print("%d" % position + 1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句