Remove final character from string

StackOverflow

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.

Answer rating: 1051

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)




Tutorials