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'.
6 Answers 6
>>> 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.
-
Be careful with the last option:
s = "helloxxxhelloxxx" s = s.replace(s[-3:], '') print s
se1by– se1by2015年10月07日 09:06:15 +00:00Commented Oct 7, 2015 at 9:06
"hello"[:-3]
- first length - 3
characters.
"hello"[:2]
- first 2 characters.
type "hello"[:2]
or "hello"[:-3] which is the answer for removing the last three letters
hope this helps
-
This is not what was requested; what was requested was to remove the last three, not take the first two.Chris Morgan– Chris Morgan2010年12月13日 07:18:35 +00:00Commented Dec 13, 2010 at 7:18
-
i just focused on the "he" from "hello" :) , its ok thoughSaif al Harthi– Saif al Harthi2010年12月13日 07:29:11 +00:00Commented Dec 13, 2010 at 7:29
"hello"[:2]
is the easiest way to do this however the accurate answer for the problem
would be as Saif al Harthi stated. "hello"[:-3]
if x is your string then you can use x[:len(x)-3:+1]
to get the desired result
-
2This works, but it is a very bad style, inefficient, redundant, and therefore bug-prone.Davidmh– Davidmh2014年08月15日 11:39:15 +00:00Commented Aug 15, 2014 at 11:39