EN
Python - remove last character from string
0
points
In this article, we would like to show you how to remove last character from the string in Python.
Quick solution:
text = "ABC"
result = text[:-1]
print("after: ", result) # AB
or:
text = "ABC"
result = text[:len(text) - 1]
print("after: ", result) # AB
Â
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 examples
1. Slicing with positive indexing
In this example, we use slicing with positive indexing to remove the last character from a string.
text = "dirask"
print("String before:", text)
# remove last character from string
text = text[:len(text) - 1]
print("String after: ", text)
Output:
String before: dirask
String after: diras
2. Slicing with negative indexing
In this example, we use slicing with negative indexing to remove the last character from the string.
text = "dirask"
print("String before:", text)
# remove last character from a string
text = text[:-1]
print("String after: ", text)
Output:
String before: dirask
String after: diras