'How can I check if only one specific word is in a string in python [duplicate]

How can I check if a string only contains one word in python.

x = "tell hello"
if "tell" == x
   print(True)
else 
   print(False)

In this case it should print False, because tell isnt the only Word in the string. But tell is always there. There is only the possibility that after tell is no Word following(in which case it should print true) and that an n amount of words is following(in which case it should print false).



Solution 1:[1]

Break the string


h = "hello my baby"

# Breaks the string into a list if ' ' are present is seperates them
words = h.split(' ')

then find the word if present in the list

if "baby" in words:
   print("present")


Edit

And Also You shouldn't use the following code


if "hello" in h:
   print("present")

because if h='hellomy baby' still output will be the same as h="hello my baby" and you don't want that

Also for faster performance one may use


words = set(h.split(' '))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1