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

PythonServer Side ProgrammingProgramming

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
raja
Published on 08-Dec-2017 10:32:09
Advertisements