Replace the last N characters in a String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 22, 2022

banner

Photo from Unsplash

Replace the last N characters in a String in Python #

To replace the last N characters in a string:

  1. Use string slicing to get a slice of the string before the last N characters.
  2. Use the addition (+) operator to append the replacement string to the result.
main.py
my_str = 'bobbyhadz.com' n = 4 new_str = my_str[:-n] + '-new' print(new_str) # 👉️ bobbyhadz-new

We used string slicing to get a slice of the string before the last N characters.

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

The slice my_str[:-n] starts at index 0 and goes up to, but not including the last N characters in the string.

We used the addition (+) operator to append the replacement to the slice.

If your replacement value is not of type string, use the str() class to convert it to a string.

main.py
my_str = 'bobbyhadz.com' n = 4 new_str = my_str[:-n] + str(1234) print(new_str) # 👉️ bobbyhadz1234

The values on the left and right-hand sides of the addition (+) operator need to be of compatible types.

Alternatively, you can use the str.rsplit() method.

Replace the last N characters in a String using str.rsplit() #

To replace the last N characters in a string:

  1. Use the str.rsplit() method to split the string on the characters, once, from the right.
  2. Use the str.join() method to join the list into a string with the specific replacement string.
main.py
my_str = 'bobbyhadz.com' new_str = '-new'.join(my_str.rsplit('.com', 1)) print(new_str) # 👉️ bobbyhadz-new

The combination of the str.rsplit() and str.join() methods is used as a single replacement from the right in Python.

The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.

main.py
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # 👉️ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # 👉️ ['bobby hadz', 'com']

The method takes the following 2 arguments:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done, the rightmost ones (optional)

Except for splitting from the right, rsplit() behaves like split().

The last step is to use the str.join() method to join the list into a string with the replacement string as a separator.

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

Which approach you pick is a matter of personal preference. I'd go with using string slicing because it's easier to read and more intuitive.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.