Last updated: Apr 10, 2024
Reading timeยท4 min
Use negative string slicing to remove the last N characters from a string,
e.g. new_string = string[:-N]
.
The slice will remove the last N characters from the string by returning a copy of the string that goes up to, but not including the last N characters.
string = 'bobbyhadz.com' # โ Remove the last 2 characters from string new_string = string[:-2] print(new_string) # ๐๏ธ bobbyhadz.c # โ Remove the last 3 characters from a string new_string = string[:-3] print(new_string) # ๐๏ธ bobbyhadz. # โ Remove the last 4 characters from a string new_string = string[:-4] print(new_string) # ๐๏ธ bobbyhadz
We used string slicing to remove the last N characters from a string.
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
.
Negative indices can be used to count backward, e.g. my_string[-1]
returns the
last character in the string and my_string[-2]
returns the second to last
item.
The slice string[:-2]
starts at index 0
and goes up to, but not including
the second to last character in the string.
string = 'bobbyhadz.com' new_string = string[:-2] print(new_string) # ๐๏ธ bobbyhadz.c
In other words, the slice returns a new string that doesn't contain the last 2 characters of the original string.
If you don't need to keep the original variable around, reassign it rather than declaring a new variable.
string = 'bobbyhadz.com' string = string[:-3] print(string) # ๐๏ธ bobbyhadz.
The slice string[:-3]
starts and index 0
and goes up to, but not including
the last 3 characters in the string.
If you only want to remove the last N characters from a string if they are equal
to a certain value, use the str.endswith()
method.
string = 'bobbyhadz.com' substring = 'com' if string.endswith(substring): string = string[:-len(substring)] print(string) # ๐๏ธ bobbyhadz.
The example only removes the last 3 characters from the string if the string ends with the specified characters.
The
str.endswith()
method returns True
if the string ends with the provided suffix, otherwise the
method returns False
.
Alternatively, you can use positive string slicing.
This is a three-step process:
0
and going up to the string's
length minus N
.string = 'bobbyhadz.com' new_string = string[:len(string)-2] print(new_string) # ๐๏ธ bobbyhadz.c new_string = string[:len(string)-3] print(new_string) # ๐๏ธ bobbyhadz. new_string = string[:len(string)-4] print(new_string) # ๐๏ธ bobbyhadz
We used the len()
function to get the length of the string.
The len() function returns the length (the number of items) of an object.
print(len('ab')) # ๐๏ธ 2 print(len('abc')) # ๐๏ธ 3
A string's length is always going to be last_index + 1
because indices are
zero-based in Python.
For example, if a string has a length of 10
, the last index in the string is
9
.
stop
index of 9
(or len(string) - 1
), you would remove the last character from the string because stop
indices are exclusive (up to but not including).Similarly, if you specify a stop
index of 8
(or len(string) - 2
), you
would remove the last 2 characters from the string.
Alternatively, you can use a for
loop.
This is a three-step process:
for
loop to iterate over the string with enumerate()
.string = 'bobbyhadz.com' new_string = '' n = 3 for index, char in enumerate(string): if index < len(string) - n: new_string += char print(new_string) # ๐๏ธ bobbyhadz.
We used the enumerate()
function to get access to the index of the current
iteration.
string = 'abc' for index, char in enumerate(string): print(char, index) # ๐๏ธ a 0, b 1, c 2
The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
On each iteration, we check if the current index is less than the string's length minus N.
This is very similar to the positive slicing approach from the previous example.
If the condition is met, we add the current character to a new string.
The +=
operator is a shorthand for new_string = new_string + char
.
Which approach you pick is a matter of personal preference. I'd use the negative string slicing approach as I find it quite direct and readable.
I've also written an article on how to remove the first N characters from a string.
You can learn more about the related topics by checking out the following tutorials: