Replace the Last or Last N characters in a String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
6 min

banner

# Table of Contents

  1. Replace the last character in a String in Python
  2. Replace the last character in a String using re.sub()
  3. Replace the last character in a String using list()
  4. Replace the last N characters in a String in Python
  5. Replace the last N characters in a String using str.rsplit()
  6. Replace characters at the end of a String using str.rpartition()

# Replace the last character in a String in Python

Use string slicing to replace the last character in a string, e.g. my_str[:-1] + '_'.

The slice of the string excludes the last character, so we can append the replacement character using the addition (+) operator.

main.py
my_str = 'bobbyhadz.com' new_str = my_str[:-1] + '_' print(new_str) # ๐Ÿ‘‰๏ธ bobbyhadz.co_

replace last character in string

The code for this article is available on GitHub

If you need to replace the last N characters in a String, click on the following subheading:

The slice my_str[:-1] starts at index 0 and goes up to, but not including the last character of the string.

main.py
my_str = 'bobbyhadz.com' print(my_str[:-1]) # ๐Ÿ‘‰๏ธ bobbyhadz.co

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 last step is to use the addition (+) operator to append the replacement string.

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

main.py
my_str = 'bobbyhadz.com' new_str = my_str[:-1] + str(123) print(new_str) # ๐Ÿ‘‰๏ธ bobbyhadz.co123

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

# Replace the last character in a String using re.sub()

Alternatively, you can use the re.sub() method.

main.py
import re my_str = 'bobbyhadz.com' new_str = re.sub(r'm$', '_', my_str) print(new_str) # ๐Ÿ‘‰๏ธ bobbyhadz.co_

replace last character in string using re sub

The code for this article is available on GitHub

The re.sub() method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

If the pattern isn't found, the string is returned as is.

The first argument we passed to the re.sub() method is the pattern we want to match in the string and the second is the replacement for the match.

The dollar sign $ matches the end of the string, so the specified character is only replaced if it's at the end of the string.

Alternatively, you can use the list() class.

# Replace the last character in a String using list()

This is a three-step process:

  1. Use the list() class to convert the string to a list of characters.
  2. Update the value of the last element in the list.
  3. Use the str.join() method to join the list into a string.
main.py
my_str = 'bobbyhadz.com' list_of_chars = list(my_str) # ๐Ÿ‘‡๏ธ ['b', 'o', 'b', 'b', 'y', 'h', 'a', 'd', 'z', '.', 'c', 'o', 'm'] print(list_of_chars) list_of_chars[-1] = '_' new_str = ''.join(list_of_chars) print(new_str) # ๐Ÿ‘‰๏ธ bobbyhadz.co_

replace last character in string using list

The code for this article is available on GitHub

We used the list() class to convert the string to a list of characters.

main.py
my_str = 'bobbyhadz.com' # ๐Ÿ‘‡๏ธ ['b', 'o', 'b', 'b', 'y', 'h', 'a', 'd', 'z', '.', 'c', 'o', 'm'] print(list(my_str))

As opposed to strings, lists are mutable, so we can directly update the value of a list element at a specific index.

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

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.

We used an empty string separator to join the list into a string without a delimiter.

# 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

replace last n character in string

The code for this article is available on GitHub

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).

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()

This is a two-step process:

  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

replace last n characters in string using split

The code for this article is available on GitHub

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.

# Replace characters at the end of a String using str.rpartition()

The str.partition method can also be used to replace characters at the end of a string.

This is a two-step process:

  1. Use the str.rpartition() method to split the string at the last occurrence of the given substring.
  2. Use the addition operator to add the replacement between the head and tail of the string.
main.py
string = '---bobby---hadz' head, _separator, tail = string.rpartition('---') print(head) # ๐Ÿ‘‰๏ธ ---bobby print(_separator) # ๐Ÿ‘‰๏ธ --- print(tail) # ๐Ÿ‘‰๏ธ hadz replacement = '===' new_string = head + replacement + tail print(new_string) # ๐Ÿ‘‰๏ธ ---bobby===hadz

replace characters at the end of a string using str rpartition

The code for this article is available on GitHub

The str.rpartition() method splits the string at the last occurrence of the provided separator.

main.py
string = '---bobby---hadz' # ๐Ÿ‘‡๏ธ ('---bobby', '---', 'hadz') print(string.rpartition('---'))

The method returns a tuple containing 3 elements - the part before the separator, the separator, and the part after the separator.

If the separator is not found in the string, the method returns a tuple containing two empty strings, followed by the string itself.

We used the addition (+) operator to add the replacement string between the head and the tail.

When used with strings, the addition (+) operator concatenates them.

main.py
print('before' + '===' + 'after') # ๐Ÿ‘‰๏ธ before===after

I've also written an article on how to replace the first or first N characters in a string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev