Python – Check if String contains Substring

Check if String contains Substring in Python

Python - Check if String contains Substring

To check if a given string contains specific substring, use membership operator in.

The syntax for condition to check if a string contains a specific substring is

substring in string

The above expression returns True if the substring is present in the string, or False if the substring is not present in the string.

Examples

1. Check if string contains a specific search string

In this example, we will take two string: one is our main string, and the other is substring. And using in operator, we will check if the substring is present in main string.

Python Program

string = 'Hello World!'
substring = 'Wor'
isSubstringPresent = substring in string
print(isSubstringPresent)
Run Code Copy

Output

True

As in operator returns a boolean value, you can use this expression as a condition in if statement.

In the following example, we will check if the string contains substring, and based on the result, we will execute a block of code conditionally using if statement.

Python Program

string = 'Hello World!'
substring = 'Wor'
if substring in string:
    print('String contains substring.')
else :
    print('String does not contain substring.')
Run Code Copy

Output

String contains substring.

2. Check if string contains, using str.find()

You can also use other methods like string.find() to check if a string contains a substring. string.find(substring) returns the index of substring in string. If the substring is present in the string, then string.find() returns a non-negative integer. We can use this as a condition, and verify if string contains substring.

Python Program

string = 'Hello World!'
substring = 'Wor'
if string.find(substring) > -1:
    print('String contains substring.')
else :
    print('String does not contain substring.')
Run Code Copy

Output

String contains substring.

Summary

In this tutorial of Python Examples, we learned how to check if a given string contains a specific substring, using membership operator, and other methods.

Related Tutorials

Code copied to clipboard successfully 👍