Python String find()
Python String.find() method returns the index of first occurrence of specified value in given string.
If the value is not present in this string, find() returns -1
.
In this tutorial, we will learn the syntax and examples for find() method of String class.
Syntax
The syntax of String find() method in Python is
str.find(value, start, end)
where
Parameter | Required/ Optional | Description |
---|---|---|
value | Required | A string. Index of this value in the string has to be returned. |
start | Optional | An integer. The index from which, the value has to be searched in this string. |
end | Optional | An integer. The index until which, the value has to be searched in this string. |
Examples
find() with default values
In this example, we will take a string 'abcd-abcd-abcd'
, and find the index of the value 'bc'
in the string.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
result = x.find(value)
print("Index :", result)
Output
Index : 2
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 . .
c d : index of 'cd' is 2
The index of first occurrence of value is 2.
Even though there are multiple occurrences of the value in this string, find() method returns only the index of first occurrence.
find() with Specific Start
In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
start = 5
result = x.find(value, start)
print("Index :", result)
Output
Index : 7
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 . .
|
start=5 from this position
c d : index of 'cd' is 7
find() with Specific Start and End
In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen and the end position up until which the search for value in the string has to happen.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
start = 5
end = 7
result = x.find(value, start, end)
print("Index :", result)
Output
Index : -1
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 11 12 13
| |
start=5 end=7
There is no occurrence of the value in this string for given start and end values.
Conclusion
In this Python Tutorial, we learned how to find the index of first occurrence of specified value in given string, using String method – find().