Amy W
Amy W

Reputation: 111

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

Upvotes: 10

Views: 21323

Answers (4)

jxramos
jxramos

Reputation: 8266

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

Upvotes: 7

Ryan
Ryan

Reputation: 734

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.

Upvotes: 1

Cydonia7
Cydonia7

Reputation: 3836

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

Upvotes: 16

Matt Ball
Matt Ball

Reputation: 359966

Use string slicing.

>>> x = 'I am going'
>>> x[:-3]
'I am go'

Upvotes: 3

Related Questions