Skip to content

Python string contains word

  • by

Use if…in the statement to check string contains the word in Python.

if word in mystring: 

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.')


Python string contains the word

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading