Replace Last N characters from a string in Python

In this article, we will discuss different ways to replace the last N characters of a string with another substring in Python.

Table Of Contents

Suppose we have a string,

"Sample String"

We want to replace the last 3 characters in this string. After replacement, the final string should be like,

"Sample StrXXX"

There are different techniques to do this. Let’s discuss them one by one.

Using Indexing

To replace the last N characters in a string using indexing, select all characters of string except the last n characters i.e. str[:-n]. Then add replacement substring after these selected characters and assign it back to the original variable. It will give us an effect that we have replaced the last N characters in string with a new substring.

For example: Replace last 3 characters in a string with “XXX”

strValue = 'Sample String'

n = 3
replacementStr = 'XXX'

# Replace last 3 characters in string with 'XXX'
strValue = strValue[:-n] + replacementStr

print(strValue)

Output:

Sample StrXXX

It replaced the last 3 characters in string with “XXX”.

Using rsplit() and join()

Split the string but from reverse direction i.e. starting from the end and while moving towards the front of string. Use the last N characters of string as delimeter and 1 as the max count of split i.e. str.rsplit(str[-n:], 1) . It returns a sequence of all characters in string except the last N characters. Then join these characters with the substring ‘XXX’ using the join() function.

For example: Replace last 3 characters in a string with “XXX”

strValue = 'Sample String'

n = 3
replacementStr = 'XXX'

# Replace last 3 characters in string with 'XXX'
strValue = replacementStr.join(strValue.rsplit(strValue[-n:], 1))

print(strValue)

Output:

Sample StrXXX

It replaced the last 3 characters in string with “XXX”.

Using Regex

The regex module provides a function regex.sub(pattern, replacement_str, original_str) . It helps to replace the substrings in string that matches the given regex pattern.

To replace the last N character in a string, pass the regex pattern “.{N}$” and replacement substring in the sub() function. This regex pattern will match only the last N characters in the string and those will be replaced by the given substring.

For example: Replace last 3 characters in a string with “XXX”

import re

strValue = 'Sample String'

# Replace last 3 characters in string with 'XXX'
strValue = re.sub(r'.{3}$', 'XXX', strValue)

print(strValue)

Output:

Sample StrXXX

Summary:

We learned about three different ways to replace the last N characters in a string in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top