Strip removing more characters than expected

前端 未结 2 709
太阳男子
太阳男子 2020-12-19 13:25

Can anyone explain what\'s going on here:

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


        
相关标签:
2条回答
  • 2020-12-19 13:49

    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'
    
    0 讨论(0)
  • 2020-12-19 13:57

    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'
    
    0 讨论(0)
提交回复
热议问题