EN
Python - replace last character in string
3 points
In this article, we would like to show you how to replace the last character in string in Python.
Quick solution:
xxxxxxxxxx
1
text = "ABC"
2
3
size = len(text) # text length
4
replacement = "X" # replace with this
5
6
text = text.replace(text[size - 1:], replacement)
7
8
print("String after: ", text) # ABX
In this example, we use replace()
method to replace the last character in text
string.
xxxxxxxxxx
1
text = "ABC"
2
3
print("String before:", text)
4
5
size = len(text) # text length
6
replacement = "X" # replace with this
7
8
text = text.replace(text[size - 1:], replacement)
9
10
print("String after: ", text) # ABX
Output:
xxxxxxxxxx
1
String before: ABC
2
String after: ABX