Use if…in the statement to check string contains the word in Python.
if word in mystring:
print('success')
but keep in mind that this matches a sequence of characters, not necessarily a whole word – for example, 'word' in 'swordsmith'
is True. If you only want to match whole words, you ought to use regular expressions:
Python string contains the word
A simple example code checks if a word is in a string in Python. If you want to do a case-insensitive search you can normalize strings using the lower()
or upper()
methods like this:
sentence = 'There are more trees on Earth than stars in the Milky Way galaxy'
word = 'milky'
if word in sentence.lower():
print('Word found.')
Output:
Do comment if you have any doubts or suggestions on this Python string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.