python - Python 2.7 严格条
问题描述
我有一个字符串string = 'some.value:so this-can be:any.thing, even some.value: too'
我想去掉'some.value:'
左边的。
我失败的尝试:
>>> string.lstrip('some.value:')
' this-can be:any.thing, even some.value: too'
>>> string.replace('some.value:','')
'so this-can be:any.thing, even too'
>>> string.split(':')[1]
'so this-can be'
预期输出:so this-can be:any.thing, even some.value: too
我认为最接近我的答案的是使用lstrip()
. 我怎样才能告诉lstrip()
去掉整个短语?
[!] 不使用任何库是首选!
注意:有一个类似的问题,但答案不适用于我。
解决方案
我们检查要剥离的字符串是否是开头,如果是则剪切字符串:
def strip_from_start(strip, string):
if string.startswith(strip):
string = string[len(strip):]
return string
print(strip_from_start('value:', 'value: xxx value: zzz'))
# xxx value: zzz
推荐阅读
- bazel - 配置环境
- android - BufferQueueProducer:[SurfaceTexture-1-12105-10] 断开连接:未连接(req=1)
- html - 如何为更多应用(例如 Google 主页)构建 9 框图标
- python - 不同列的总和
- python - 在刻面图上绘制参考线
- xml - 如何使用 sed 仅替换特定 xml 块内的文本?
- python - Selenium 错误即“selenium.common.exceptions.ElementNotInteractableException:消息:元素不可交互”
- sql - mysql表中两列之间的公共值
- arrays - 在数组字段(可变长度)上应用 Udf 并将其拆分为 pyspark 中的列
- git - 如何通过终端创建拉取请求?