Python – Check if String Contains Substring
In this tutorial, we are going to see different ways to check if a string contains substring and if it does, look for its index. Also, we will check the existence of a substring ignoring the case.
Check if String Contains Substring Using ‘IN’ operator
The “in” operator in Python can be used to check if a given string exists in another string. For example:
str = "Welcome to StackHowTo." # Check if String Contains Substring if "StackHowTo" in str: print ('Substring found') else: print('Substring not found')
Output:
Substring found[st_adsense]
Check if String Contains Substring Using ‘NOT IN’ operator
We can also use the ‘NOT IN’ operator to check the opposite scenario. For example:
str = "Welcome to StackHowTo." # Check if String Contains Substring if "StackHowTo" not in str: print('Substring not found') else: print ('Substring found')
Output:
Substring found
Check if String Contains Substring in a Case-insensitive Way
To check whether a given string contains a substring in a case-insensitive way, i.e. ignoring case, we must first transform both strings to lowercase, and then use the “in” or “not in” operator to check if substring exist. For example:
str = "Welcome to StackHowTo." # Convert both strings to lowercase if "STACKHOWTO".lower() in str.lower(): print ('Substring found') else: print('Substring not found')
Output:
Substring found[st_adsense]
Check if String Contains Substring Using Regex
We can also use python’s regex “re” module to check if a given string exists within another string. For example:
import re str = "Welcome to StackHowTo." # Create a pattern to match the string 'StackHowTo motif = re.compile("StackHowTo") # searches for the pattern in the string and returns the corresponding object obj = motif.search(str) # check if the object is not Null if obj: print ('Substring found') else: print('Substring not found')
Output:
Substring found[st_adsense]