Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip removing more characters than expected

Tags:

python

string

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'
like image 581
ericksonla Avatar asked Dec 15 '15 18:12

ericksonla


1 Answers

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'
like image 77
senshin Avatar answered Oct 04 '22 00:10

senshin