How to remove the last n characters of a string in python

Python program to remove the last n characters of a string:

This post will show you how to remove the last n characters from a string in Python. Python provides different ways to manipulate string. String is immutable. We cann’t change a string variable directly. But we can create one different string modifying the original one.

Our objective is to remove the last n characters from a string where n is less than or equal to the size of the string. For example, if the string is hello and if we remove the last two characters, it will print hel.

The easiest way to implement this is by using string slicing and rstrip methods. In this post, we will learn how to use string slicing and rstrip with example.

Remove last n characters of a string using string slice in python:

String slicing can be done as below in python:

str[start:stop]

If we call this method on a string str, it will start slicing from the index start and it will stop at index stop. It excludes the character at index stop.

If you consider the below example:

given_str = "Hello World"

print(given_str[1:3])
print(given_str[1:10])
print(given_str[:10])
print(given_str[2:])

It will print the below output:

el
ello Worl
Hello Worl
llo World

As you can see, the start and stop indices are optional. If we don’t give start, it takes 0. Also, if we don’t give stop, the slicing ends at the end of the string.

To remove last characters from a string, we need to use negative indexing. For that we will not pass any value for start and one negative integer for stop. For [:-n], it will remove all n characters from the end of the string.

Below is the complete program:

given_str = "Hello World"

print(given_str[:-2])
print(given_str[:-5])
print(given_str[:-20])

It will print:

Hello Wor
Hello 
  • The first one deleted the last two characters
  • Second one deleted last five characters
  • Last one deleted all characters because 20 is greater than the string size.

Remove last n characters from a string using rstrip:

rstrip function is defined as below:

str.rstrip([s])

We can pass one string s optionally to this method. It will remove the substring in the given string. If we don’t provide any substring, it will remove all whitespaces at the end of the string.

For example:

given_str = "Hello World"

print(given_str.rstrip('rld'))

It will print:

Hello Wo

So, if we pass the last characters of the string, it will remove them:

given_str = "Hello World"

print(given_str.rstrip('d'))
print(given_str.rstrip('ld'))
print(given_str.rstrip('rld'))
print(given_str.rstrip('World'))
print(given_str.rstrip('ello World'))

It will print:

Hello Worl
Hello Wor
Hello Wo
Hello 
H

You can go with any of these methods. string slicing can be used for index based deletion and rstrip can be used for substring based deletion.

You might also like: