14-Mar-2023
.
Admin
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.
#Python