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

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Be careful with the last option: s = "helloxxxhelloxxx" s = s.replace(s[-3:], '') print s
4

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

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

Comments

1

type "hello"[:2]

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

hope this helps

2 Comments

This is not what was requested; what was requested was to remove the last three, not take the first two.
i just focused on the "he" from "hello" :) , its ok though
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]

Comments

-2

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

1 Comment

This works, but it is a very bad style, inefficient, redundant, and therefore bug-prone.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.