Languages
[Edit]
EN

Python - remove last n characters from string

0 points
Created by:
OneCricketer
460

In this article, we would like to show you how to remove last n characters from the string in Python.

Quick solution:

string = string[:len(string) - n]

or:

string = string[:-n]

 

1. Slicing with positive indexing

Overview

string[start_index: end_index]

Where:

  • start_index -  index position, from where it will start fetching the characters (default value is 0),
  • end_index -  index position, where it will end fetching the characters (default value is end of the string),

We also use len() function to get the string length.

Practical example

In this example, we use slicing with positive indexing to remove the last n characters from a string.

string = "ABCDE"
n = 3

print("String before:", string)

# remove last n characters from string
string = string[:len(string) - n]

print("String after: ", string)

Output:

String before: ABCDE
String after:  AB

2. Slicing with negative indexing

In this example, we use slicing with negative indexing to remove the last n characters from a string.

string = "ABCDE"
n = 3

print("String before:", string)

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

print("String after: ", string)

Output:

String before: ABCDE
String after:  AB
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - remove last n characters from string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join