How to Replace Last Character Occurrence in Python String?
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.
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?