4

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'.

asked Dec 13, 2010 at 6:47
0

6 Answers 6

12
>>> s = "hello"
>>> print(s[:-3])
he

For an explanation of how this works, see the question: good primer for python slice notation.

answered Dec 13, 2010 at 6:49
8

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.

answered Dec 13, 2010 at 9:19
1
  • Be careful with the last option: s = "helloxxxhelloxxx" s = s.replace(s[-3:], '') print s Commented Oct 7, 2015 at 9:06
4

"hello"[:-3] - first length - 3 characters.

"hello"[:2] - first 2 characters.

answered Dec 13, 2010 at 6:51
1

type "hello"[:2]

or "hello"[:-3] which is the answer for removing the last three letters

hope this helps

answered Dec 13, 2010 at 6:51
2
  • This is not what was requested; what was requested was to remove the last three, not take the first two. Commented Dec 13, 2010 at 7:18
  • i just focused on the "he" from "hello" :) , its ok though Commented Dec 13, 2010 at 7:29
0

"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]

axel22
32.4k10 gold badges127 silver badges139 bronze badges
answered Aug 29, 2011 at 16:03
-2

if x is your string then you can use x[:len(x)-3:+1] to get the desired result

Martin Tournoij
28k24 gold badges110 silver badges158 bronze badges
answered Aug 15, 2014 at 11:24
1
  • 2
    This works, but it is a very bad style, inefficient, redundant, and therefore bug-prone. Commented Aug 15, 2014 at 11:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.