How to check if a string contains a substring in Python

 In python, in operator will do the trick.

>>> 'is' in 'What is this!'

>>> True

or you could use string method s.find()

>>> s = 'What is this!'

>>> s.find('is')

>>> 5

>>> s.find('was')

>>> -1

If find() found the substring, it returns the index where the substring first appears. Otherwise it returns -1.

Under the hood, python will use __contains__(self, item), __iter__(self), and __getitem__(self, key) in that order to determine whether a substring is in a string. 

Comments