Python search for a substring | Example code

Use the in operator to search for a substring in Python. 99% of use cases will be covered using the keyword, in, which returns True or False:

if "blah" in somestring: 

Python search for a substring Example

Use the in comparison operator because

  1. the language intends its usage, and
  2. other Python programmers will expect you to use it.
sentence = "This be a string"

sub_str = "string"

if sub_str in sentence:
    print("Found the string.")


Python search for a substring

Using find method

If it’s just a substring search you can use string.find(“substring”).

Or use case of getting the index, use str.find (which returns -1 on failure, and has optional positional arguments):

s = "This be a string"
sub_str = "string"
if s.find(sub_str) == -1:
    print("Not here!")
    print("Found the string.")


Found the string.

Note: You do have to be a little careful with find, index, and in though, as they are substring searches.

Do comment if you have any doubts and suggestions on this Python string topic/

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.