Finding the Position of a Specific Character Using find() and rfind()
How would you find which position the character "a"
is in within the string "banana"
?
The find()
and rfind()
functions 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 refers to a number representing the order. In a string composed of multiple characters, each character has an index, and it starts from 0. For example, in the string
"hello"
, the index of"h"
is 0, and the index of"e"
is 1.
Spaces in a string are also counted as part of the index. 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 right (end) 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.