I have a string in python and I'd like to take off the last three characters. How do I go about this?
So turn something like 'hello' to 'he'.
>>> s = "hello"
>>> print(s[:-3])
he
For an explanation of how this works, see the question: good primer for python slice notation.
Here's a couple of ways to do it.
You could replace the whole string with a slice of itself.
s = "hello"
s = s[:-3] # string without last three characters
print s
# he
Alternatively you could explicitly strip the last three characters off the string and then assign that back to the string. Although arguably more readable, it's less efficient.
s = "hello"
s = s.rstrip(s[-3:]) # s[-3:] are the last three characters of string
# rstrip returns a copy of the string with them removed
print s
# he
In any case, you'll have to replace the original value of the string with a modified version because they are "immutable" (unchangeable) once set to a value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With