Finding the position of a word in a string

后端 未结 2 1313
春和景丽
春和景丽 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: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.

提交回复
热议问题