How to Replace Last Occurrence in Python String?
Hi Dev,
This tutorial will provide example of how to replace last occurrence in python string. this example will help you python replace last occurrence in string. I would like to share with you how to replace last occurrence of string in python. I would like to show you how to replace only last occurrence of string in python.
In this example, i will add myString variable with hello string. Then we will use replace() function to replace last occurrence from string in python. So, without further ado, let's see simple examples: You can use these examples with python3 (Python 3) version.
Example
main.py
# Declare String Variable
myString = "Hello, THIS is nicesnippets.com, THIS is awesome."
# Substring that need to be replaced
findStr = 'THIS'
# Replacement following string
replaceStr = 'THAT'
# Replace Logic
myString = replaceStr.join(myString.rsplit(findStr, 1))
print(myString)
Output:
Hello, THIS is nicesnippets.com, THAT 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?