EN
Python - custom string contains() method
0 points
In this article, we would like to show you how to check if the string contains a substring in Python.
Quick solution:
xxxxxxxxxx
1
text = "ABC"
2
print("BC" in text) # True
In this example, we use in
operator to create a custom implementation of the string contains()
method and check if text
contains some words.
xxxxxxxxxx
1
text = "dirask is cool"
2
3
word_1 = "cool"
4
word_2 = "abc"
5
6
7
def contains(string, phrase):
8
return phrase in string
9
10
11
print(contains(text, word_1)) # True
12
print(contains(text, word_2)) # False
Output:
xxxxxxxxxx
1
True
2
False
Note:
You can also use
string.find()
method to find index of the specified substring.xxxxxxxxxx
1text = "dirask is cool"
2print(text.find("is")) # 7