【发布时间】:2017-01-29 18:34:57
【问题描述】:
我正在编写一个代码,提示用户输入一个定义为 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: ")
for eachWord in str1:
if str2 in str1:
print("That word was found at index position", str1.index(str2)+1)
else:
print("Sorry that word was not found")
虽然结果似乎打印了是否在 str1 中为句子中的每个单词找到了单词的索引值一次?例如,如果 str1 是“apples oranges lemons limes pears”,我选择了“apples”这个词,它会想出:
That word was found at index position: 1
That word was found at index position: 1
That word was found at index position: 1
That word was found at index position: 1
That word was found at index position: 1
如果有人可以帮助我和尝试类似的事情的其他人,那将非常有帮助!谢谢! :)
【问题讨论】:
-
只是在给定字符串中找到搜索词的位置吗?
-
是的,这是正确的,如果给定字符串中有 2 个或多个相同的单词,我希望它能够打印它们的索引位置
-
如果你用空格分割,那么如何在列表中的一个元素中重复一个单词?除非您有像
cancan这样的词并且正在搜索词can。您还使用循环for eachWord in str1:,然后永远不要使用eachWord!您在每次迭代中都进行相同的搜索。
标签: python string python-3.x for-loop