我正在编写一个代码,提示用户输入一个句子,然后将其定义为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柠檬柠檬青柠梨”,而我选择了“ 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


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

最佳答案

代码的问题是您使用了for eachWord in str1。这意味着您要遍历str1中的每个字符,而不是每个单词。要解决此问题,请使用str1.split()分隔单词。您还应该在for循环之外使用if str2 in str2;检查str2是否在str1中,然后遍历str1,而不是遍历str1,并且每次都检查它是否包含str2。一次,您将无法使用str1.split().index()查找所有位置,因为index()始终返回列表中某个项目的最低位置。

一个更简单的方法是使用list comprehension

positions=[x for x in range(len(str1.split()))if str1.split()[x]==str2]


这将包含str2str1.split()的所有索引。

最终代码:

positions=[x for x in range(len(str1.split()))if str1.split()[x]==str2]
if positions:
    for position in positions:
        print("That word was found at index position",position)
else:
    print("Sorry that word was not found")


输入:

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


输出:

That word was found at index position 3
That word was found at index position 7

关于python - 在Python 3中使用for循环在字符串中查找值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41924497/

10-13 01:12