Use the find()
method to check if a string has certain substring.
The method returns the index of the first occurrence of the given value.
Remember the index count starts at 0.
phrase = "This is a regular text"
print(phrase.find('This'))
print(phrase.find('regular'))
print(phrase.find('text'))
0
10
18
If the value is not found, the return will be -1
.
phrase = "This is a regular text"
print(phrase.find('train'))
-1
You can also choose to begin the search in a specific position and end it in another specific position of the string.
phrase = "This is a regular text"
#look for in 'This is', the rest of the phrase is not included
print(phrase.find('This', 0, 7))
#look for in 'This is a regular'
print(phrase.find('regular', 0, 17))
#look for in 'This is a regul'
print(phrase.find('a', 0, 15))
0
10
8