766

How do I remove the last character from a string?

"abcdefghij"  →  "abcdefghi"
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
user1675111
  • 8,695
  • 4
  • 18
  • 14
  • 19
    **I don't believe this to be a duplicate.** In the other question, the OP asked for a substring in general. This OP asks for a _very_ specific substring which is often very useful. I believe having this here for people to search AND for people to answer is useful. It would be nice for someone who may want 1) to take off a trailing os separator character from a bunch of paths _or_ 2) to remove a last comma on each line of a CSV which has an empty last column _or_ 3) to remove a trailing period/full stop (any punctuation) from the end of a bunch of sentence strings ... [more examples, no chars] – bballdave025 Aug 26 '20 at 20:31
  • 2
    Especially when one is new to programming, asking one to figure out the `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]` – bballdave025 Aug 26 '20 at 20:50
  • 3
    I do believe this to be a duplicate of [How do I get a substring of a string in Python?](https://stackoverflow.com/questions/663171/how-do-i-get-a-substring-of-a-string-in-python). The accepted answer shows how to use `[:-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. – mkrieger1 Aug 09 '21 at 22:25

6 Answers6

1225

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)
Hari
  • 1,561
  • 4
  • 17
  • 26
Cyrille
  • 13,905
  • 2
  • 22
  • 41
  • 5
    Yes, `st[-1]` is only the last character of `st` – Cyrille Mar 18 '13 at 13:45
  • 7
    Actually that slice will still work even if `st` is empty. Well, it will return an empty string still, but you won't get an error. – kindall Mar 18 '13 at 13:58
  • 2
    What if you have a list of words and you want to delete the last character of every word? [blue, red, green] => [blu,re,gree] ? – Jellyse Apr 09 '18 at 10:19
  • 12
    `[i[:-1] for i in ['blue','red','green']]` – Cyrille Apr 09 '18 at 13:34
  • 7
    Looking at the examples, it is worth to mention that lists are mutable and that `list.pop()` method is the way to go when dealing with lists, as it removes the last item in place `O(1)`, while `[:-1]` slicing creates a copy of a list without the last element in `O(n-1)` time plus `O(n-1)` space. Strings are immutable - so nothing to add. – Dmitry Sep 19 '19 at 05:26
56

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'
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
11

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
Nico
  • 858
  • 10
  • 20
4

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'
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • 1
    This merely seems to restate the earlier answers. – tripleee Oct 07 '22 at 06:33
  • @tripleee Perhaps, but the only well-written answer is [Anshul Goyal's](https://stackoverflow.com/a/57724550/365102), and even that doesn't directly describe that the basic slicing syntax takes the form (`start:stop`), which also solves the question *"How do I remove the first N characters from a string?"*. For a newcomer, I imagine that `[:-1]` looks like unexplained magic. Lastly, this answer also gives some indication of how `:-1` corresponds to `:len(s) - 1`. – Mateen Ulhaq Oct 07 '22 at 09:03
0

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
Arslanex
  • 43
  • 2
0
input_str = "abcdefghij"
output_str = ''.join(input_str.rsplit(input_str[-1], 1))
print(output_str)  # Output: "abcdefghi"

In this method, input_str.rsplit(input_str[-1], 1) splits the string at the last occurrence of the last character, resulting in a list of substrings. Then, ''.join() concatenates those substrings back into a single string without the last character. The resulting string is stored in output_str.

This approach may be useful if you want to remove only the last occurrence of a specific character from the string, rather than removing the very last character in general.

Kevin O.
  • 355
  • 3
  • 11