Skip to Content

Python – Remove Last N Characters From String

In this tutorial, we will look at how to remove the last n characters from a string in Python with the help of some examples.

remove last n characters from string in python

Python strings are immutable which means that they cannot be modified. However, you can create a copy of the string with the last n characters removed and assign it to the original string variable.

To remove the last n characters from a string, slice the string from its start to the index of the nth character from the end. Using negative indexing can be helpful here. The following is the syntax –

# remove last n characters from a string
s = s[:-n]

It returns a copy of the original string with the last n characters removed.

Let’s look at some examples -.

In this case n = 2, hence we slice the string from its starting index (which is 0) to -2 (which represents the index of the 2nd last character in the string).

# create a string
s = "THIS IS SPARTAAA"
# remove last 2 characters
print(s[:-2])

Output:

THIS IS SPARTA

You can see that the resulting string does not have the last two characters from the original string.

We can similarly use the above syntax to remove the last three characters from a string.

# create a string
s = "THIS IS SPARTAAA"
# remove last 3 characters
print(s[:-3])

Output:

THIS IS SPART

The resulting string has the last three characters removed.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.