Finding the Position of a Specific Character Using find() and rfind()
How can you find the position of the character "a"
in the string "banana"
?
The find()
and rfind()
functions are used to locate the position of a specific character or substring within a string.
How to Use the find() Function
The find()
function searches for a specified character or substring from the beginning (left) of the string and returns the index number of its starting position.
What is an index? : In programming, an index is a number that represents the position of a character in a string, starting from 0. For example, in
"hello"
,"h"
has index 0, and"e"
has index 1.
Spaces are also counted as characters when indexing a string. If the substring appears multiple times, the find()
function returns the index of its first occurrence.
If the character or substring does not exist in the string, it returns -1
.
text = "Python class, class is fun"
# Return the starting position of "class" from the beginning of the text string
position = text.find("class")
# Return the starting position of the first occurrence of "class" from the left
print(position)
In the string "Python class, class is fun"
, each character is assigned an index as follows:
0: 'P'
1: 'y'
2: 't'
3: 'h'
4: 'o'
5: 'n'
6: ' '
7: 'c'
8: 'l'
9: 'a'
10: 's'
...
In the code above, the find()
function searches for the substring "class"
in the string text
from the left.
The substring "class"
begins at the 7th index, so the find()
function returns 7
, the start position of "class"
.
How to Use the rfind() Function
The rfind()
function searches for a specified character or substring starting from the end (right) of the string and returns its index.
If the character or substring is not found, it returns -1
.
text = "Python class, class is fun"
# Return the starting position of "class" from the end of the text string
position = text.rfind("class")
# Return the starting position of the first occurrence of "class" from the right
print(position)
The rfind()
function searches for the substring "class"
in the string text
from the right.
The substring "class"
starts at the 14th index, so the rfind()
function returns 14
, the start position when searched from the right.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.