我正在编写一个代码,提示用户输入一个句子,然后将该句子定义为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循环在str2中查找str1以打印是否找到该单词,以及是否找到该单词,以及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


如果有人可以帮助我以及其他任何尝试类似的事情,那将非常有帮助!

最佳答案

只要确保在if / else语句中使用比较,然后考虑一下循环在做什么。

希望这足够简单但有效:

编辑:添加一个计数器,而不是使用“ .index()”。只要保持它的好和基本:

str1In = "I like to code a few things and code a lot"
str2 = "code"
str1 = str1In.split()

indexCount = 0
for word in str1:
    if word == str2:
       print("Your word was found at index point",int(indexCount))
    else:
       print("Your word was not found at",int(indexCount))
    indexCount += 1

09-05 14:41
查看更多