问题描述
谁能解释一下这里发生了什么:
s = 'REFPROP-MIX:METHANOL&WATER's.lstrip('REFPROP-MIX') # 这会按预期返回 ':METHANOL&WATER's.lstrip('REFPROP-MIX:') # 返回 'THANOL&WATER'
那个我"怎么了?冒号是 lstrip 的特殊字符吗?这尤其令人困惑,因为它按预期工作:
s = 'abc-def:ghi's.lstrip('abc-def') # 返回 ':ghi's.lstrip('abd-def:') # 返回 'ghi'
str.lstrip
从字符串中删除其参数中的所有字符,从左边开始.由于左前缀REFPROP-MIX:ME"中的所有字符都在参数REFPROP-MIX:"中,所有这些字符都被删除.同样:
str.lstrip
不会从左边删除整个字符串(长度大于 1).如果要这样做,请使用以 ^
开头的正则表达式:
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'
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'
这篇关于去除比预期更多的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!