这是我的代码:
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
if keyword in words:
pos = words.index(keyword)
pos = 0+1
print(pos)
对,这就是我所拥有的,但如果该单词重复,那么它只显示第一个位置。有什么想法吗?
最佳答案
试试这个:
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
for (i, subword) in enumerate(words):
if (subword == keyword):
print(i+1)
关于python - 查找字符串中某个单词重复的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33153821/