Does Python have a string 'contains' substring method?
Yes, Python has a string method called str.__contains__() that allows you to check if a string contains another string.
Yes, Python has a string method called str.__contains__() that allows you to check if a string contains another string. You can also use the in keyword to check if a string contains another string. Note: The in operator is the recommended, Pythonic way to check for substrings.
Here is an example of how to use the str.__contains__() method:
Using string's __contains__() method in Python to find a substring inside it
string = "Hello, World!"
substring = "World"
# Using the str.__contains__() method
if string.__contains__(substring):
print("The substring '{}' is present in the string '{}'.".format(substring, string))
else:
print("The substring '{}' is not present in the string '{}'.".format(substring, string))
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
And here is an example of how to use the in keyword:
Using Python in operator to check if a substring exists inside a string
sentence = "The quick brown fox jumps over the lazy dog."
if "cat" in sentence:
print("The string contains the substring 'cat'.")
else:
print("The string does not contain the substring 'cat'.")