【发布时间】:2017-06-22 15:53:20
【问题描述】:
我正在编写一个代码,提示用户输入一个定义为str1的句子,然后提示输入一个定义为str2的单词。
例如:
Please enter a sentence: i like to code in python and code things
Thank you, you entered: i like to code in python and code things
Please enter a word: code
我想使用for 循环在str1 中查找str2 以打印是否找到该单词,如果已找到,则显示str2 的索引位置。
目前我有这个代码:
str1Input = input("Please enter a sentence: ")
print("Thank you, you entered: ",str1Input)
str1 = str1Input.split()
str2 = input("Please enter a word: ")
if str2 in str1:
for str2 in str1:
print("That word was found at index position", str1.index(str2)+1)
else:
print("Sorry that word was not found")
虽然,结果似乎打印是否找到索引位置,但随后打印句子中每个单词的索引位置。此外,如果我正在搜索在该句子中出现两次的某个单词,它只会打印该单词在该句子中第一次出现的索引位置,例如:
Please enter a sentence: i like to code in python and code things
Please enter a word: code
Thank you, you entered: i like to code in python and code things
That word was found at index position: 1
That word was found at index position: 2
That word was found at index position: 3
That word was found at index position: 4
That word was found at index position: 5
That word was found at index position: 6
That word was found at index position: 7
That word was found at index position: 4
That word was found at index position: 9
如果有人可以帮助我和其他尝试类似事情的人,那将非常有帮助!
【问题讨论】:
标签: python string python-3.x for-loop indexing