
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to replace the last occurrence of an expression in a string in Python?
This problem can be solved by reversing the string, reversing the string to be replaced,replacing the string with reverse of string to be replaced with and finally reversing the string to get the result.
You can reverse strings by simple slicing notation - [::-1]. To replace the string you can use str.replace(old, new, count). For example,
def rreplace(s, old, new): return (s[::-1].replace(old[::-1],new[::-1], 1))[::-1] rreplace('Helloworld, hello world, hello world', 'hello', 'hi')
This will give the output:
'Hello world,hello world, hi world'
Another method by which you can do this is to reverse split the string once on the old string and join the list with the new string. For example,
def rreplace(s, old, new): li = s.rsplit(old, 1) #Split only once return new.join(li) rreplace('Helloworld, hello world, hello world', 'hello', 'hi')
This will give the output:
'Hello world, hello world, hi world'
- Related Articles
- Python - Replace duplicate Occurrence in String
- How to find index of last occurrence of a substring in a string in Python?
- How to get the last index of an occurrence of the specified value in a string in JavaScript?
- String function to replace nth occurrence of a character in a string JavaScript
- C program to replace all occurrence of a character in a string
- Finding the last occurrence of a character in a String in Java
- How to find the last occurrence of an element in a Java List?
- Get the last occurrence of a substring within a string in Arduino
- How to find the nth occurrence of substring in a string in Python?
- Create a polyfill to replace nth occurrence of a string JavaScript
- Last occurrence of some element in a list in Python
- How to count the occurrence of a specific string in a string in JavaScript
- How to convert an object x to an expression string in Python?
- How to replace all occurrences of a string with another string in Python?
- How to get everything before the last occurrence of a character in MySQL?

Advertisements