English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python string find() usage and example

Python string methods

The find() method returns the index value of the first occurrence of the substring (if found). If not found, it returns-1.

The syntax of the find() method is:

str.find(sub[, start[, end]])

find() parameter

The find() method can use up to three parameters:

  • sub- It is the substring to be searched in the str string.

  • startandend (Optional)-Search for the substring str[start:end] in it

find() return value

The find() method returns an integer value.

  • If the substring exists in the string, it returns the index of the first occurrence of the substring.

  • If the substring does not exist in the string, it returns-1.

Example1: find() without start and end parameters

quote = 'Let it be, let it be, let it be'
result = quote.find('let it')
print("Substring 'let it':", result)
result = quote.find('small')
print("Substring 'small':", result)
# How to use find()
if (quote.find('be,') != -1)
  print("Contained string 'be,'")
else:
  print("Not contained string")

The output when running the program is:

Substring 'let it': 11
Substring 'small': -1
Contains string 'be,'

Example2: find() with start and end parameters

quote = 'Do small things with great love'
# Search for substring 'hings with great love'
print(quote.find('small things', 10))
# Search for substring ' small things with great love' 
print(quote.find('small things', 2))
# Search for substring 'hings with great lov'
print(quote.find('o small ', 10, -1))
# Search for substring 'll things with'
print(quote.find('things ', 6, 20))

The output when running the program is:

-1
3
-1
9

Python string methods