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

rectangletangle
  • 50,393
  • 94
  • 205
  • 275

6 Answers6

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

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

Community
  • 1
  • 1
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
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.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Be careful with the last option: `s = "helloxxxhelloxxx" s = s.replace(s[-3:], '') print s` – se1by Oct 07 '15 at 09:06
4

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

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

khachik
  • 28,112
  • 9
  • 59
  • 94
1

type "hello"[:2]

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

hope this helps

Saif al Harthi
  • 2,948
  • 1
  • 21
  • 26
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,045
  • 9
  • 125
  • 137
user875531
  • 57
  • 1
  • 7
-2

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

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146