Finding the position of a word in a string

后端 未结 2 1316
春和景丽
春和景丽 2020-12-10 15:35

With:

sentence= input(\"Enter a sentence\")
keyword= input(\"Input a keyword from the sentence\")

I want to find the position of the keywor

相关标签:
2条回答
  • 2020-12-10 15:41

    This is what str.find() is for :

    sentence.find(word)
    

    This will give you the start position of the word (if it exists, otherwise -1), then you can just add the length of the word to it in order to get the index of its end.

    start_index = sentence.find(word)
    end_index = start_index + len(word) # if the start_index is not -1
    
    0 讨论(0)
  • 2020-12-10 15:43

    If with position you mean the nth word in the sentence, you can do the following:

    words = sentence.split(' ')
    if keyword in words:
        pos = words.index(keyword)
    

    This will split the sentence after each occurence of a space and save the sentence in a list (word-wise). If the sentence contains the keyword, list.index() will find its position.

    EDIT:

    The if statement is necessary to make sure the keyword is in the sentence, otherwise list.index() will raise a ValueError.

    0 讨论(0)
提交回复
热议问题