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.
Advertisements
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.
How do I remove the last character from a string?
"abcdefghij" → "abcdefghi"
Mateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges
asked Mar 18, 2013 at 13:33
3
Simple:
my_str = "abcdefghij"
my_str = my_str[:-1]
Try the following code snippet to better understand how it works by casting the string as a list:
str1 = "abcdefghij"
list1 = list[str1]
print[list1]
list2 = list1[:-1]
print[list2]
In case, you want to accept the string from the user:
str1 = input["Enter :"]
list1 = list[str1]
print[list1]
list2 = list1[:-1]
print[list2]
To make it take away the last word from a sentence [with words separated by whitespace like space]:
str1 = input["Enter :"]
list1 = str1.split[]
print[list1]
list2 = list1[:-1]
print[list2]
Hari
1,1283 gold badges14 silver badges23 bronze badges
answered Mar 18, 2013 at 13:34
CyrilleCyrille
13.3k2 gold badges17 silver badges38 bronze badges
5
What you are trying to do is an extension of string slicing in Python:
Say all strings are of length 10, last char to be removed:
>>> st[:9]
'abcdefghi'
To remove last N
characters:
>>> N = 3
>>> st[:-N]
'abcdefg'
answered Aug 30, 2019 at 9:56
Anshul GoyalAnshul Goyal
69.1k36 gold badges142 silver badges175 bronze badges
The simplest solution for you is using string slicing.
Python 2/3:
source[0: -1] # gets all string but not last char
Python 2:
source = 'ABC'
result = "{}{}".format[{source[0: -1], 'D']
print[result] # ABD
Python 3:
source = 'ABC'
result = f"{source[0: -1]}D"
print[result] # ABD
answered Jun 8, 2021 at 13:38
NicoNico
8489 silver badges20 bronze badges
So there is a function called rstrip[] for stuff like this. You enter the value you want to delete, in this case last element so string[-1] :
string = "AbCdEf"
newString = string.rstrip[string[-1]]
print[newString]
If you runt his code you shouul see the 'f' value is deleted.
OUTPUT: AbCdE
answered May 3 at 18:57
Using slicing, one can specify the start
and stop
indexes to extract part of a string s
. The format is s[start:stop]
. However, start = 0
by default. So, we only need to specify stop
.
Using stop = 3
:
>>> s = "abcd"
>>> s[:3]
'abc'
Using stop = -1
to remove 1
character from the end [BEST METHOD]:
>>> s = "abcd"
>>> s[:-1]
'abc'
Using stop = len[s] - 1
:
>>> s = "abcd"
>>> s[:len[s] - 1]
'abc'
answered Apr 25 at 0:14
Mateen UlhaqMateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges