How to replace the last occurrence of an expression in a string in Python?

In this article, we are going to learn how to replace the last occurrence of an expression in a string.

In Python, String manipulation is a common task, and Python provides the built-in method named replace(). Though we can replace the specified character or substring in a string using this method, it does not directly support replacing the last occurrence. To achieve this we need to use slicing, string splitting, or a regular expression.

Using rfind() Method

The rfind() method searches for the starting index of the last occurrence of the specified substring. We can use this index with slicing to construct a new string, replacing only the last occurrence.

Syntax

str.rfind(value, start, end)

Example

Let's replace the last occurrence of 'BMW' with 'Vespa' in the string "Rx100, BMW, Activa, BMW" ?

vehicles = "Rx100, BMW, Activa, BMW"
old_text = "BMW"
new_text = "Vespa"

last_index = vehicles.rfind(old_text)
if last_index != -1:
    result = vehicles[:last_index] + new_text + vehicles[last_index + len(old_text):]
else:
    result = vehicles

print("Original:", vehicles)
print("Modified:", result)
Original: Rx100, BMW, Activa, BMW
Modified: Rx100, BMW, Activa, Vespa

Using rsplit() Method

The rsplit() method splits the string into a list of substrings, starting from the right end. By limiting the split to 1 occurrence, we can isolate the last occurrence and replace it using join().

Syntax

str.rsplit(separator, maxsplit)

Example

Here we replace the last occurrence of "Hi" with "Vanakam" ?

greetings = "Hi, Hello, Hi, Namaste"
old_text = "Hi"
new_text = "Vanakam"

parts = greetings.rsplit(old_text, 1)
result = new_text.join(parts)

print("Original:", greetings)
print("Modified:", result)
Original: Hi, Hello, Hi, Namaste
Modified: Hi, Hello, Vanakam, Namaste

Using re.sub() Method

The re.sub() method can replace patterns using regular expressions. To replace the last occurrence, we reverse the string and pattern, replace the first match (originally the last), then reverse the result back.

Example

Let's replace the last occurrence of '112' with 'ABC' in the string '112-232-112-345' ?

import re

text = "112-232-112-345"
pattern = "112"
replacement = "ABC"

# Reverse string, pattern, and replacement
reversed_text = text[::-1]
reversed_pattern = pattern[::-1]
reversed_replacement = replacement[::-1]

# Replace first occurrence in reversed string
replaced = re.sub(reversed_pattern, reversed_replacement, reversed_text, count=1)

# Reverse back to get final result
result = replaced[::-1]

print("Original:", text)
print("Modified:", result)
Original: 112-232-112-345
Modified: 112-232-ABC-345

Comparison

Method Complexity Best For
rfind() Simple Exact string matches
rsplit() Medium Clean, readable code
re.sub() Complex Pattern-based replacements

Conclusion

Use rfind() with slicing for simple string replacements. The rsplit() approach offers cleaner code, while re.sub() provides flexibility for pattern-based replacements.

Updated on: 2026-03-24T16:53:10+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements