Divyansh_C Divyansh_C - 1 year ago 44
Python Question

Find and select a required word from a sentence?

I am trying to get

from user and then find a required word from that input. If the required word is there, then a function runs. So I tried
to split the input but how do I find if the required word is in the list.

Answer Source

It's really simple to get this done. Python has an in operator that does exactly what you need. You can see if a word is present in a string and then do whatever else you'd like to do.

sentence = 'hello world'
required_word = 'hello'

if required_word in sentence:
    # do whatever you'd like

You can see some basic examples of the in operator in action here.

Depending on the complexity of your input or lack of complexity of your required word, you may run into some problems. To deal with that you may want to be a little more specific with your required word.

Let's take this for example:

sentence = 'i am harrison'
required_word = 'is'

This example will evaluate to True if you were to doif required_word in sentence: because technically the letters is are a substring of the word "harrison".

To fix that you would just simply do this:

sentence = 'i am harrison'
required_word = ' is '

By putting the empty space before and after the word it will specifically look for occurrences of the required word as a separate word, and not as a part of a word.

HOWEVER, if you are okay with matching substrings as well as word occurrences then you can ignore what I previously explained.