python - str.lstrip() 意外行为

标签 python

我正在做一个 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/

相关文章:

python - 当我打印 id 时,它与 "inspect element"中的 id 不匹配

python - 如何使用pytest测试异步功能?

python - 从子进程的标准输出的 tar 中读取单个文件

python - 使用 anaconda 更新到 python 3.7

python - 输出相同时不覆盖文件的简单方法

python - 美汤如何刮经纬度

python - ubuntu 14.04 如何从 13.3 升级到 scipy 14.0

python - 从 xpath 中的多个子节点中选择文本

python - SharePoint在线: Get site user id using Office365-REST-Python-Client library

python - 如何将轮盘赌轮背景图像添加到 matplotlib 雷达图