Python - Check if a string contains a substring

By xngo on June 7, 2019

#!/usr/bin/python3
# Description: Check if a string contains a substring.
 
str = 'openwritings.net'
sub_str = 'writings'
 
# Use in operator to check if a string contains another string.
if sub_str in str:
    print("{} is in {}".format(sub_str, str))
else:
    print("{} is NOT in {}".format(sub_str, str))
 
 
# Or use find() function. find() returns -1 if substring doesn't exist. 
#   Otherwise, it returns the index position of the substring.
if str.find(sub_str) == -1:
    print("{} is NOT in {}".format(sub_str, str))
else:
    print("{} is in {}".format(sub_str, str))

Output

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.