Skip to content

Find substring in string python | Example code

  • by

Use find() method to find substring in string python. If the string is found then this method returns the index of the first occurrence of the substring and If not found, it returns -1.

str.find(sub,start,end)

Start and End are optional parameters by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search.

Example Find substring in string python

Simple python example code- How to use find() in if statement.

word = 'Python programing tutorials and examples'

# returns first occurrence of Substring
result = word.find('Python')
print("Substring 'Python' index:", result)

# How to use find() in if statement
if word.find('and') != -1:
    print("Substring Found")
else:
    print("Substring Not Found")

Output:

Find substring in string python

find() With start and end Arguments

word = 'Python programing tutorials and examples'

# Substring is searched in full string
print(word.find('Python', 0))

# Substring is searched in ' programing tutorials and examples'
print(word.find('small things', 6))

# Substring is searched in 'programing tutorials and example'
print(word.find('and', 10, -1))

Output:

0
-1
28

Do comment if you have any doubts and suggestions on this Python substring 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