Does Python Have a String “contains” Substring Method?
The short answer is: “Yes.” Here’s how to use it
For those unfamiliar with Java, the .contains() method belongs to the String class, returning true or false if the supplied substring is present. This is similar to the .includes() method in JavaScript.
To be comprehensive, identifying a substring is answering one of two questions: “Is the substring present?” and “Where is the substring present?” Both can be answered in Python, but each question has its own solution.
Is the Substring Present?
To answer the question of whether the substring is present, use the in keyword.
The in keyword is meant to search through an iterable, such as dictionaries or lists. Strings are also an iterable data type and the resulting expression will return True or False, based on evaluation.a = "Shinra"
print("ra" in a) # True
print("tai" in a) # False
This method is the most straightforward and Pythonic, although the boolean answer it gives is limited.
Where Is the Substring Present?
To find out not only if a substring is present, but where as well, use the .find() method which is included in the String class.
Similar to .indexOf() in JavaScript, the .find() method will return the starting index position of a given substring. In the event that the substring is not found, the value -1 will be returned.a = "Shinra"
print(a.find("ra")) # 4
print(a.find("tai")) # -1
This method is beneficial as you can simply take the return and, using the expression >= 0, derive the same answer as using the in keyword.a = "Shinra"
if a.find("ra") >= 0:
# substring was found