Mastering Substring Search in Python: A Comprehensive Guide
If you want to check if a string is a substring of another string, you can use the in and not in operators. Let’s say we want to test if "like" is a substring of string of string s. Here is how we
do it using the in operator. The in operator will evaluate to True if "like” is a substring of s and False if it is not.
s = 'Please find something you like'
if 'like' in s:
print('Like is a substring of s')
else:
print('Like is not a substring of s')
Output:
Like is a substring of s
We can also use the not in operator. The not in operator is the opposite of the in operator.
s = 'Please find something you like'
if 'like' not in s:
print('Like is not a substring of s')
else:
print('Like is a substring of s')
Output:
Like is a substring of s
Python advises only using the find() method to know the position of a substring. If we wanted to find the position of ‘something’ in a string, here is how we use the find() method. The find method returns the index where the substring starts.
s = 'Please find something you like'
print(s.find('something'))
Output:
12