Computer >> Computer tutorials >  >> Programming >> Python

Does Python have a string 'contains' substring method?


No python doesn't have a 'contains' substring method. Instead you could use either of the below 2 methods:

Python has a keyword 'in' for finding if a string is a substring of another string. For example,

>>> 'ello' in 'hello world'
True
>>> 'no' in 'hello'
False

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,

>>> 'hello world'.find('ello')
1
>>> 'hello'.find('no')
-1