How to find the last occurrence of a character in a python string

Python program to find the last occurrence of a character in a string

Introduction :

In this post, we will learn how to find the last occurrence of a character in a string in Python. We will write one python program that will take the character and string as inputs from the user and find out the last occurrence of that character in the string.

Algorithm to use :

We will use the below Algorithm for this problem :

  1. Get the string from the user and store it in a variable.
  2. Get the character from the user and store it in another variable.
  3. Find out the last occurrence of the character in the string
  4. Print out the last occurrence position.

Solution 1 : By using rindex() method :

rindex() method is used to find the last index of a character or substring in a string. It finds the last index and returns the value. If the character or substring is not found in that string, it throws one ValueError.

Below example program illustrates how rindex() works :

given_str = input("Enter a string : ")
given_char = input("Enter a character : ")

char_index = given_str.rindex(given_char)

print(char_index)

Here,

  • We are taking the string as input from the user and storing that value in given_str
  • Similarly, we are reading the character and storing that value in given_char
  • The last occurrence of given_char in given_str is found using rindex and it is stored in char_index
  • The last line prints out the index value

Sample Output :

Enter a string : hello world
Enter a character : o
7

Enter a string : hello world
Enter a character : x
Traceback (most recent call last):
    File "example.py", line 6, in <module>
    char_index = given_str.rindex(given_char)
ValueError: substring not found

The first example prints the last occurrence of character ‘o’ in the string ‘hello world’. The second example throws an error because character x doesn’t exist in that string.

Solution 2: By using rfind() :

rfind() is similar to rindex(). It finds the last occurrence of a string or character in a string. If the string/character is found, it returns that value, else it returns -1, not an exception.

Let’s try rfind() with the above example :

given_str = input("Enter a string : ")
given_char = input("Enter a character : ")

char_index = given_str.rfind(given_char)

print(char_index)

Sample Output :

Enter a string : hello world
Enter a character : o
7

Enter a string : hello world
Enter a character : x
-1

As you can see here, it returns -1 if the character/word is not found.