Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

How do I check if ‘ello’ is contained in the string ‘hello world’?

How do I also check if ‘no’ is contained in the string ‘Harry Potter: The Goblet of Fire’?


1 Answer
Rajendra Dharmkar

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.