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?

B S
  • 100
  • 1
  • 2
  • 7

1 Answers1

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.

bbd108
  • 958
  • 2
  • 10
  • 26
  • 1
    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. – Adam Smith Nov 21 '18 at 07:42
  • 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]` – Rohit-Pandey Nov 21 '18 at 07:45