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. You can also use the in
keyword to check if a string contains another string.
Here is an example of how to use the str.__contains__()
method:
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))
Watch a video course
Python - The Practical Guide
And here is an example of how to use the in
keyword:
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'.")