Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim characters in Python?

Very new to Python and have very simple question. I would like to trim the last 3 characters from string. What is the efficient way of doing this?

Example I am going becomes I am go

like image 643
Amy W Avatar asked Aug 13 '11 22:08

Amy W


4 Answers

Slicing sounds like the most appropriate use case you're after if it's mere character count; however if you know the actual string you want to trim from the string you can do an rstrip

x = 'I am going'
>>> x.rstrip('ing')
'I am go'
>>> x.rstrip('noMatch')
'I am going'

UPDATE

Sorry to have mislead but these examples are misleading, the argument to rstrip is not being processed as an ordered string but as an unordered set of characters.

all of these are equivalent

>>> x.rstrip('ing')
'I am go'
>>> x.rstrip('gni')
'I am go'
>>> x.rstrip('ngi')
'I am go'
>>> x.rstrip('nig')
'I am go'
>>> x.rstrip('gin')
'I am go'

Update 2

If suffix and prefix stripping is being sought after there's now dedicated built in support for those operations. https://www.python.org/dev/peps/pep-0616/#remove-multiple-copies-of-a-prefix

like image 172
jxramos Avatar answered Oct 16 '22 19:10

jxramos


You can use new_str = old_str[:-3], that means all from the beginning to three characters before the end.

like image 45
Cydonia7 Avatar answered Oct 16 '22 19:10

Cydonia7


Use string slicing.

>>> x = 'I am going'
>>> x[:-3]
'I am go'
like image 45
Matt Ball Avatar answered Oct 16 '22 18:10

Matt Ball


You could add a [:-3] right after the name of the string. That would give you a string with all the characters from the start, up to the 3rd from last character. Alternatively, if you want the first 3 characters dropped, you could use [3:]. Likewise, [3:-3] would give you a string with the first 3, and the last 3 characters removed.

like image 21
Ryan Avatar answered Oct 16 '22 20:10

Ryan