Guidelines

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 help 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 indexes. If the substring appears multiple times, find() returns the index of its first occurrence.

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

Example Usage of find()
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 given string "Python class, class is fun", the characters are indexed as follows:

String Index
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" starts 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.

Example Usage of rfind()
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.

Mission
0 / 1

The rfind() function searches for a substring starting from the beginning (left) of the string and returns the index.

O
X

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result