Pavle Jonoski
By Pavle Jonoski

Check if a string contains substring in Python

Check if a string contains substring in Python

String contains method in Python

Python’s alternative to String.contains is the keyword in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21


foobar = 'foobar'

substr = 'foo'



if substr in foobar:

    print('Yes')

else:

    print('No')



# Prints 'Yes'

Although under the hood Python may use some of the magic methods like

__contains__, __iter__ and __getitem__, you should try to avoid using

these methods directly on strings. These are useful when defining your own type

with testing membership capabilities.