Find the last occurrence of a character in a string using Python

Hey Coder! today we are going to learn how to find the last occurrence of a character in a string using Python.

The approaches would be:

  1. By using an in-built rfind() function.
  2. By placing a pointer and iterating from the end of the string.

Approach 1: using find() function

In Python, we directly have a function named rfind() for finding the last occurrence of a character in a given string.

Here, we are going to return the index of the last occurrence of the character.
So, let us implement it.

Example Code:

s = 'Hello Everyone!!'
ch = 'e'
res = s.rfind(ch)
print(res)

Run this code online
We need to pass a parameter (character) inside the rfind() function.

Output:

13

In the above example, the last occurrence of the character ‘e’ is at index 13.

 

Approach-2: By placing a pointer to find the last occurrence of a character in a string using Python

Now, let us code the given question manually, by taking a pointer variable at the end of the string.
In this approach, we are going to iterate from the back of the string and print the index of the last occurrence of the character.

Let us implement it.

s = 'Anudeep Pulluri'
ch = 'u'
k=len(s)-1
while k>=0:
    if s[k]==ch:
        break
    k-=1 
print(k)

Run this code online
In the above code, we are finding the length of the string and iterating from the end of the loop.

And, when the match is found we will be out of the loop as we are using the break statement and printing the index value.

Output:

12

These are the two simple approaches for finding the last occurrence of a character in a string.

Keep learning!

Lastly, You can refer to the below articles on your interest:

Leave a Reply

Your email address will not be published.