How to check if a substring is contained in another string in Python



Python has a keyword 'in' for finding if a string is a substring of another string. For example

print('ello' in 'hello world') 

OUTPUT

True

If you also need the first index of the substring, you can use find(substr) to find the index. If this method returns -1, it means that substring doesn't exist in the string. For example,

print("hello world".find('ello'))

OUTPUT

 1

Checking if  ‘no’ is contained in the string ‘Harry Potter: The Goblet of Fire'

print("Harry Potter: The Goblet of Fire".find('no'))

OUTPUT

-1

Advertisements