
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace Last Occurrence of 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'
Advertisements