Skip to content

Python search for a substring | Example code

  • by

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: 
    continue

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.")

Output:

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!")
else:
    print("Found the string.")

Output:

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading