3

I'm trying to delete the last character of a string, and every documentation I can find says that this works.

string = 'test'
string[:-1]
print(string)

However, whenever I try it, my IDE tells me that line two has no effect, and when I run the code it outputs "test" and not "tes", which is what I want it to do. I think that the documentation I'm reading is about python 2 and not 3, because I don't understand why else this simple code wouldn't work. Can someone show me how to remove the last letter of a string in python 3?

1
  • 6
    string = string[:-1] Do this. Commented Nov 21, 2018 at 7:39

1 Answer 1

7
new_string = string[:-1]
print(new_string)

You must save the string in the memory. When we assign a variable to the string without the last character, the variable then "stores" the new value. Thus we can print it out.

Sign up to request clarification or add additional context in comments.

2 Comments

This demonstrates the correct code, but doesn't explain any of the why. Try expanding on this answer to mention that strings are immutable, that string slicing creates a new object and doesn't modify an existing one, etc.
If you want to see changes in string after altering it , you have to assign alteration of string in same string or another string.Thats why we do string = string[:-1]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.