Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Manipulation in Python

Tags:

python

string

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

like image 243
rectangletangle Avatar asked Nov 28 '22 19:11

rectangletangle


2 Answers

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

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

like image 149
Greg Hewgill Avatar answered Dec 06 '22 18:12

Greg Hewgill


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.

like image 33
martineau Avatar answered Dec 06 '22 19:12

martineau