How do I remove the last character from a string?
"abcdefghij" → "abcdefghi"
my_str[:-1]
from the answers in the dup link seems a bit of a jump. As the linked site appears RIGHT NOW (see the lynx
command), it's hard to find. $ lynx -dump https://web.archive.org/web/20200826203245/https://stackoverflow.com/questions/663171/how-do-i-get-a-substring-of-a-string-in-python | grep -n "\[[:][-]1\]"
\n 540:
print(a[:-1])
\n 542:
In the above code, [:-1] declares to print from the starting till the
\n 548: ` Note: Here a [:-1] is also the same as a [0:-1] and a [0:len(a)-1]
[:-2]
for removing the last two characters of a string. I believe it should be not too hard for any programmer to infer that [:-1]
can then be used to remove only the final character.
Simple:
my_str = "abcdefghij"
my_str = my_str[:-1]
Try the following code snippet to better understand how it works by casting the string as a list:
str1 = "abcdefghij"
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)
In case, you want to accept the string from the user:
str1 = input("Enter :")
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)
To make it take away the last word from a sentence (with words separated by whitespace like space):
str1 = input("Enter :")
list1 = str1.split()
print(list1)
list2 = list1[:-1]
print(list2)
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'
The simplest solution for you is using string slicing.
Python 2/3:
source[0: -1] # gets all string but not last char
Python 2:
source = 'ABC'
result = "{}{}".format({source[0: -1], 'D')
print(result) # ABD
Python 3:
source = 'ABC'
result = f"{source[0: -1]}D"
print(result) # ABD
So there is a function called rstrip() for stuff like this. You enter the value you want to delete, in this case last element so string[-1] :
string = "AbCdEf"
newString = string.rstrip(string[-1])
print(newString)
If you runt his code you shouul see the 'f' value is deleted.
OUTPUT: AbCdE
Using slicing, one can specify the start
and stop
indexes to extract part of a string s
. The format is s[start:stop]
. However, start = 0
by default. So, we only need to specify stop
.
Using stop = 3
:
>>> s = "abcd"
>>> s[:3]
'abc'
Using stop = -1
to remove 1
character from the end (BEST METHOD):
>>> s = "abcd"
>>> s[:-1]
'abc'
Using stop = len(s) - 1
:
>>> s = "abcd"
>>> s[:len(s) - 1]
'abc'
Success story sharing
st[-1]
is only the last character ofst
st
is empty. Well, it will return an empty string still, but you won't get an error.[i[:-1] for i in ['blue','red','green']]
list.pop()
method is the way to go when dealing with lists, as it removes the last item in placeO(1)
, while[:-1]
slicing creates a copy of a list without the last element inO(n-1)
time plusO(n-1)
space. Strings are immutable - so nothing to add.