遍历句子中的单词,并给出某个单词在句子中的位置,可以通过以下步骤实现:
以下是一个示例代码:
def find_word_position(sentence, target_word):
words = sentence.split()
position = []
for index, word in enumerate(words):
if word == target_word:
position.append(index)
return position
# 示例用法
sentence = "I love programming and programming loves me"
target_word = "programming"
result = find_word_position(sentence, target_word)
print(f"The word '{target_word}' is found at position(s): {result}")
输出结果:
The word 'programming' is found at position(s): [2, 4]
在这个例子中,句子是"I love programming and programming loves me",目标单词是"programming"。通过遍历单词列表,我们找到了目标单词在位置2和位置4的位置。
领取专属 10元无门槛券
手把手带您无忧上云