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

Popular posts from this blog

How to create a memory puzzle game with Python and Pygame (#005)

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

Introduction to multitasking with Python #003 gevent (2020 tutorial)