Let's say my string is 10 characters long.
How do I remove the last character?
If my string is "abcdefghij"
(I do not want to replace the 'j'
character, since my string may contain multiple 'j'
characters) I only want the last character gone. Regardless of what it is or how many times it occurs, I need to remove the last character from my string.
Simple:
st = "abcdefghij"
st = st[:-1]
There is also another way that shows how it is done with steps:
list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
This is also a way with user input:
list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
To make it take away the last word in a list:
list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)
What you are trying to do is an extension of string slicing in Python:
Say all strings are of length 10, last char to be removed:
>>> st[:9]
'abcdefghi'
To remove last N
characters:
>>> N = 3
>>> st[:-N]
'abcdefg'
Source: Stackoverflow.com