Skip to content

Python if statement string contains substring or word | Example code

  • by

Best to check string contains substring or not is using the in operator in Python. The in operator is generally used with if statement to check string contains a word or not.

99% of use cases will be covered using the keyword, in, which returns True or False:

if "blah" not in somestring: 
    continue

Note: Does Python have a string ‘contains’ substring method

Python example Check if String Contains Substring

Simple python example code.

fullstring = "EyeHunt Python tutorial"
substring = "Python"

if substring in fullstring:
    print("Found!")
else:
    print("Not found!")

Output:

Python if statement string contains substring word

If it’s just a substring search you can use

string.find("substring")

Complete code

s = "This be a string"
if s.find("is") == -1:
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")

Output: Found ‘is’ in the string.

Do comment if you have any doubts and suggestions on this Python condition statement 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