Python String - Replace last occurrence


Python String - Replace last occurrence

To replace only the last occurrence in a string in Python, you can use string replace() method with string reversal, or find the index of last occurrence of old string and replace it with the new string.

For example, if given string is

"Hello, World! Hello, Universe!"

and we need to replace only the last occurrence of "Hello" with "Hi", then the resulting string would be

"Hello, World! Hi, Universe!"

In this tutorial, you will learn how to replace the last occurrence in a string in Python using the two approaches that we have mentioned in the beginning.

1. Replace last occurrence in string using string reversal and string replace() method in Python

In this example, we are given a string in x. We have to replace only the last occurrence of specified old substring with a new value using replace() method.

Steps

  1. Given string is in x.
x = "Hello, World! Hello, Universe!"
  1. Given old substring and new (replacement) value in old_substring and new_substring respectively.
old_substring = "Hello"
new_substring = "Hi"
  1. Reverse all the strings: x, old_substring, and new_substring into x_reversed, old_substring_reversed, and new_substring_reversed respectively. Please refer Python string reverse to see how to reverse a string. In this example, we shall use Python slicing to reverse the string.
  2. Call replace() method on string x_reversed, and pass old_substring_reversed, new_substring_reversed, and 1 as arguments. The third parameter specifies the number of replacements to be done
x_reversed.replace(
    old_substring_reversed,
    new_substring_reversed,
    1)
  1. The replace() method returns the resulting string. But, this is in reversed order. Revise this returned value, and you will get the required resulting string.

Program

The complete Python program to replace the last occurrence in a string using Python string replace() method and string reversal.

Python Program

# Input string
x = "Hello, World! Hello, Universe!"

# Substring to be replaced
old_substring = "Hello"

# Replacement string
new_substring = "Hi"

# Reverse the strings
x_reversed = x[::-1]
old_substring_reversed = old_substring[::-1]
new_substring_reversed = new_substring[::-1]

# Replace
result_string_reversed = x_reversed.replace(
                    old_substring_reversed,
                    new_substring_reversed,
                    1)

# Get result string
result_string = result_string_reversed[::-1]

# Print the result
print(f"Original : {x}")
print(f"Result   : {result_string}")

Output

Original : Hello, World! Hello, Universe!
Result   : Hello, World! Hi, Universe!

Only the last occurrence of old substring has been replaced with the new substring.

2. Replace last occurrence in string using string rfind() method in Python

In this example, we are given a string in x. We have to replace only the last occurrence of specified old substring with a new value using replace() method.

Steps

  1. Given string is in x.
x = "Hello, World! Hello, Universe!"
  1. Given old substring and new (replacement) value in old_substring and new_substring respectively.
old_substring = "Hello"
new_substring = "Hi"
  1. Find the last occurrence of old_substring in x.
last_occurrence_index = x.rfind(old_substring)
  1. Using the last occurrence of the old substring, the lengths of old substring and new substring, make the replacement using string slicing and string concatenation.
x[:last_occurrence_index] + new_substring + x[last_occurrence_index + len(old_substring):]
  1. The replace() method returns the resulting string. But, this is in reversed order. Revise this returned value, and you will get the required resulting string.

Program

The complete Python program to replace the last occurrence in a string using string rfind() method.

Python Program

# Input string
x = "Hello, World! Hello, Universe!"

# Substring to be replaced
old_substring = "Hello"

# Replacement string
new_substring = "Hi"

# Find the last occurrence of the old_substring
last_occurrence_index = x.rfind(old_substring)

# Replace
result_string = x[:last_occurrence_index] + new_substring + x[last_occurrence_index + len(old_substring):]

# Print the result
print(f"Original : {x}")
print(f"Result   : {result_string}")

Output

Original : Hello, World! Hello, Universe!
Result   : Hello, World! Hi, Universe!

Only the last occurrence of old substring has been replaced with the new substring.

Summary

In this tutorial of Python Examples, we learned how to replace only the last occurrence of a substring in a string using string replace() method with string reversal, or string rfind() method with string slicing and string concatenation, with the help of detailed step by step process and an example programs.