我正在做一个 scrapy 项目并试图解析我的配置
字符串是 attr_title
我必须去掉 'attr_' 并得到 title
。我使用了 lstrip('attr_'),但得到了意想不到的结果。我知道 lstrip
计算组合并删除它们,但很难理解它。
In [17]: "attr.title".lstrip('attr.')
Out[17]: 'itle'
PS:我知道有多种提取字符串的解决方案,我有兴趣了解这一点。
最佳答案
lstrip
迭代
结果字符串,直到没有更多的组合匹配最左边的字符集
下面是一个小插图。
In [1]: "attr.title".lstrip('attr.')
Out[1]: 'itle' # Flow --> "attr." --> "t" --> Next char is 'i' which does not match any combination hence, iteration stops & end result ('itle') is returned
In [2]: "attr.tritle".lstrip('attr.')
Out[2]: 'itle' # "attr." --> "t" --> "r" --> Next char is 'i' which does not match any combination hence, iteration stops & end result ('itle') is returned
In [5]: "attr.itratitle".lstrip('attr.')
Out[5]: 'itratitle' # "attr." --> Next char is 'i' which does not match any combination hence, iteration stops & end result ('itratitle') is returned
关于python - str.lstrip() 意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31488854/