EN
Python - remove last character from string if condition
0 points
In this article, we would like to show you how to conditionally remove last character from the string in Python.
Quick solution:
xxxxxxxxxx
1
text = "ABC"
2
3
if text[-1] == "C":
4
text = text[:-1]
5
6
print("after: ", text) # AB
In this example, we check if the last character in a string is C
and remove it if true.
xxxxxxxxxx
1
text = "ABC"
2
3
print("String before:", text)
4
5
# remove last character from a string if condition
6
if text[-1] == "C":
7
text = text[:-1]
8
9
print("String after: ", text)
Output:
xxxxxxxxxx
1
String before: ABC
2
String after: AB