Remove final character from string Remove final character from string python python

Remove final character from string


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