Skip to content

All topics  /  Python

How to Replace Last Character Occurrence in Python String?

Python ·

Hi Dev,

This post will give you an example of how to replace the last character occurrence in a python string. I would like to share with you that python replaces the last character occurrence in a string. I’m going to show you how to replace the last character occurrence of a string in python. you will learn how to replace only the last character occurrence of a string in python.

in this example, I will add myString variable with hello string. Then we will use the join() and rsplit() functions to replace the last character occurrence from a string in python. So, without further ado, let's see simple examples: You can use these examples with the python3 (Python 3) version.

Example


main.py

# Declare String Variable
myString = "Hello, This is nicesnippets.com, This is awesome."

  
# Substring that needs to be replaced
findStr   = 'T'

  
# Replacement the following string
replaceStr = 'X'

  
# Replace Logic for the last character
myString = replaceStr.join(myString.rsplit(findStr, 1))

  
print(myString)

Output:

Hello, This is nicesnippets.com, Xhis is awesome.