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
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
You can use new_str = old_str[:-3]
, that means all from the beginning to three characters before the end.
Use string slicing.
>>> x = 'I am going'
>>> x[:-3]
'I am go'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With