In this article, we shall see how to check if a string is a substring to another string or a larger string. There are multiple ways to do this. Let us look at them one by one with an example for each. First, let us see understand what a substring is?
What is a substring?
In formal language theory and computer science, a substring is a contiguous sequence of characters within a string. For instance, “the best of” is a substring of “It was the best of times”.
The following methods can be used to identify a substring.
- “in” keyword
- split() method
- find() method
- search() method
The “in” keyword
The first method is using the “in” keyword. Python has a builtin keyword called in, which will take two strings and return true if the first string exists in the second one or it will return false.
string1 in string2
True or False
Let us look at the implementation of this method with an example for both the cases true and false.
is_exists = 'str' in 'string' print(is_exists) # True
Since the substring str exists in the string string, the method returns True.
The split() method
As we all know the split method takes a string and a separator value and splits the string based on the number of occurrences of the separator.
We will be using this technique to identify the substring.
How does it work?
If the separator value is not a substring then the split method returns the same string in a list. Otherwise, it will give us a list of strings. So by checking the number of strings in the list, we can identify if a string is a substring or not. The count will be greater than one if the string is a substring.
list_of_strings = 'string'.split('str') print(list_of_strings) # ['', 'ing'] length = len(list_of_strings) print(length) # 2 if length > 1: print("substring") else: print("Not a substring")
The output of the above example is,
Let us look at the other example also.
list_of_strings = 'string'.split('abc') print(list_of_strings) # ['', 'ing'] length = len(list_of_strings) print(length) # 2 if length > 1: print("substring") else: print("Not a substring")
The output of this code is,
Not a substring
The find() method
The find() method will check if a substring exists in a string and return the index of the first character of the substring if exists, otherwise, it will return -1.
Index of the first character if the substring exists. Otherwise it will return -1.
I have typed it out in the interactive console.
The search() method
The search() method is provided by the regular expression module and it is not available directly like the above methods.
This method will return an object which have information like the indexes from where the substring begins and ends, if the substring exists in the string. Otherwise, it will not return anything.
Hope this article is helpful. If you have any queries leave them in the comments below.