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:
xxxxxxxxxx
1
text = "ABC"
2
result = text[:-1]
3
print("after: ", result) # AB
or:
xxxxxxxxxx
1
text = "ABC"
2
result = text[:len(text) - 1]
3
print("after: ", result) # AB
xxxxxxxxxx
1
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.
In this example, we use slicing with positive indexing to remove the last character from a string.
xxxxxxxxxx
1
text = "dirask"
2
3
print("String before:", text)
4
5
# remove last character from string
6
text = text[:len(text) - 1]
7
8
print("String after: ", text)
Output:
xxxxxxxxxx
1
String before: dirask
2
String after: diras
In this example, we use slicing with negative indexing to remove the last character from the string.
xxxxxxxxxx
1
text = "dirask"
2
3
print("String before:", text)
4
5
# remove last character from a string
6
text = text[:-1]
7
8
print("String after: ", text)
Output:
xxxxxxxxxx
1
String before: dirask
2
String after: diras