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.
We will use the below Algorithm for this problem :
- Get the string from the user and store it in a variable.
- Get the character from the user and store it in another variable.
- Find out the last occurrence of the character in the string
- Print out the last occurrence position.
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)
- We are taking the string as input from the user and storing that value in givenstr_
- Similarly, we are reading the character and storing that value in givenchar_
- The last occurrence of givenchar_ in givenstr_ is found using rindex and it is stored in charindex_
- The last line prints out the index value
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.
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)
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.