Write a Python program to Remove the Last Occurrence of a Character in a String using For Loop, while loop, and functions with an example.
Python Program to Remove the Last Occurrence of a Character in a String Example 1
This python program allows the user to enter a string and a character. Next, it finds and removes the last character occurrence inside a given string using For Loop.
TIP: Please refer String article to understand everything about Python Strings.
First, we used For Loop to iterate characters in a String. Inside the Python For Loop, we are using If Statement to check the character is equal to ch or not. If true, it uses the string slice index to remove that character.
NOTE: Even though, if it finds multiple matches, it traverses until it finds the last character. Because to exit from a loop, we are not using the Break statement.
# Python Program to Remove Last Occurrence of a Character in a String string = input("Please enter your own String : ") char = input("Please enter your own Character : ") string2 = '' length = len(string) for i in range(length): if(string[i] == char): string2 = string[0:i] + string[i + 1:length] print("Original String : ", string) print("Final String : ", string2)

Python Program to Delete Last Character Occurrence in a String Example 2
This python code to remove the last occurrence of a character is the same as above. However, we just replaced the For Loop with While Loop.
# Python Program to Remove Last Occurrence of a Character in a String string = input("Please enter your own String : ") char = input("Please enter your own Character : ") string2 = '' length = len(string) i = 0 while(i < length): if(string[i] == char): string2 = string[0 : i] + string[i + 1 : length] i = i + 1 print("Original String : ", string) print("Final String : ", string2)

Python Program to Delete Last Occurrence of a String Character Example 3
This Python delete last occurrence string character code is the same as the first example — however, this time, we used Functions to separate the logic.
# Python Program to Remove Last Occurrence of a Character in a String def removeLastOccur(string, char): string2 = '' length = len(string) i = 0 while(i < length): if(string[i] == char): string2 = string[0 : i] + string[i + 1 : length] i = i + 1 return string2 str1 = input("Please enter your own String : ") char = input("Please enter your own Character : ") print("Original String : ", str1) print("Final String : ", removeLastOccur(str1, char))
