Languages
[Edit]
EN

Python - remove last 2 characters from string

0 points
Created by:
MMORex
450

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

Quick solution:

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

or:

string = string[:-2]

 

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 2 characters from a string.

string = "ABCD"

print("String before:", string)

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

print("String after: ", string)

Output:

String before: ABCD
String after:  AB

2. Slicing with negative indexing

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

string = "ABCD"

print("String before:", string)

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

print("String after: ", string)

Output:

String before: ABCD
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.

Python - string (popular problems)

Python - remove last 2 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