Last updated: Apr 9, 2024
Reading timeยท6 min
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.
my_str = 'bobbyhadz.com' new_str = my_str[:-1] + '_' print(new_str) # ๐๏ธ bobbyhadz.co_
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.
my_str = 'bobbyhadz.com' print(my_str[:-1]) # ๐๏ธ bobbyhadz.co
The syntax for string slicing is my_str[start:stop:step]
.
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.
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.
Alternatively, you can use the re.sub()
method.
import re my_str = 'bobbyhadz.com' new_str = re.sub(r'm$', '_', my_str) print(new_str) # ๐๏ธ bobbyhadz.co_
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.
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.
This is a three-step process:
list()
class to convert the string to a list of characters.str.join()
method to join the list into a string.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_
We used the list()
class to convert the string to a list of characters.
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.
To replace the last N characters in a string:
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).
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.
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.
This is a two-step process:
str.rsplit()
method to split the string on the characters, once,
from the right.str.join()
method to join the list into a string with the specific
replacement string.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.
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:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At 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.
The str.partition
method can also be used to replace characters at the end of
a string.
This is a two-step process:
str.rpartition()
method to split the string at the last occurrence
of the given substring.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
The str.rpartition() method splits the string at the last occurrence of the provided separator.
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.
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.
print('before' + '===' + 'after') # ๐๏ธ before===after
I've also written an article on how to replace the first or first N characters in a string.
You can learn more about the related topics by checking out the following tutorials: