EN
Python - remove last 3 characters from string
0
points
In this article, we would like to show you how to remove last 3 characters from the string in Python.
Quick solution:
string = string[:len(string) - 3]
or:
string = string[:-3]
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 is0
),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 3
characters from a string.
string = "ABCDE"
print("String before:", string)
# remove last 3 characters from string
string = string[:len(string) - 3]
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 3
characters from a string.
string = "ABCDE"
print("String before:", string)
# remove last 3 characters from a string
string = string[:-3]
print("String after: ", string)
Output:
String before: ABCDE
String after: AB