ericksonla
ericksonla

Reputation: 1363

Strip removing more characters than expected

Can anyone explain what's going on here:

s = 'REFPROP-MIX:METHANOL&WATER'
s.lstrip('REFPROP-MIX')   # this returns ':METHANOL&WATER' as expected
s.lstrip('REFPROP-MIX:')   # returns 'THANOL&WATER'

What happened to that 'ME'? Is a colon a special character for lstrip? This is particularly confusing because this works as expected:

s = 'abc-def:ghi'
s.lstrip('abc-def')   # returns ':ghi'
s.lstrip('abd-def:')  # returns 'ghi'

Upvotes: 7

Views: 3234

Answers (2)

jpp
jpp

Reputation: 164623

The method mentioned by @PadraicCunningham is a good workaround for the particular problem as stated.

Just split by the separating character and select the last value:

s = 'REFPROP-MIX:METHANOL&WATER'
res = s.split(':', 1)[-1]  # 'METHANOL&WATER'

Upvotes: 0

senshin
senshin

Reputation: 10350

str.lstrip removes all the characters in its argument from the string, starting at the left. Since all the characters in the left prefix "REFPROP-MIX:ME" are in the argument "REFPROP-MIX:", all those characters are removed. Likewise:

>>> s = 'abcadef'
>>> s.lstrip('abc')
'def'
>>> s.lstrip('cba')
'def'
>>> s.lstrip('bacabacabacabaca')
'def'

str.lstrip does not remove whole strings (of length greater than 1) from the left. If you want to do that, use a regular expression with an anchor ^ at the beginning:

>>> import re
>>> s = 'REFPROP-MIX:METHANOL&WATER'
>>> re.sub(r'^REFPROP-MIX:', '', s)
'METHANOL&WATER'

Upvotes: 13

Related Questions