10

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

smci
  • 32,567
  • 20
  • 113
  • 146
Amy W
  • 111
  • 1
  • 1
  • 3

4 Answers4

16

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

Cydonia7
  • 3,744
  • 2
  • 23
  • 32
  • More generally, negative indexes on strings and lists refer to the end of the sequence, e.g., string[-1] is the last character. – Colin Valliant Aug 13 '11 at 22:24
7

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

jxramos
  • 7,356
  • 6
  • 57
  • 105
3

Use string slicing.

>>> x = 'I am going'
>>> x[:-3]
'I am go'
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

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.

Ryan
  • 712
  • 7
  • 21