Python String find() Method

Last Updated:

Python String find()

The find() method returns the index value of the first occurrence of the substring in the given string within the specified limit.

Note: The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found, whereas the find() method returns -1.

Example

Python Compiler
txt = "Python is simple, Python is great" x = txt.find("Python") print(x)

Syntax

txt.find(sub, start, end)

Parameter Values

ValueTypeExplanation
sub Required Specifies the substring to be searched.
start Optional Specifies the index position to start the search.
Default value is 0.
end Optional Specifies the index position to end the search.
Default value is the length of the given string (txt).

Return Value

ValueExplanation
Number Return the lowest index in the string where substring is found.
-1 If the substring is not found.

More Examples

Check if position 5 to 32 has the substring "Python":

Example

Python Compiler
txt = "Python is simple, Python is great" x = txt.find("Python", 5, 32) print(x)

Example

In the following example, we will find the difference between the find() and index() methods.

Python Compiler
txt = "Python is simple, Python is great" x = txt.find("world") print(x) y = txt.index("world") print(y)

Share this Page

Meet the Author