首页 > 解决方案 > 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()去掉整个短语?

[!] 不使用任何库是首选!

注意:有一个类似的问题,但答案不适用于我。

标签: pythonstringstrip

解决方案


我们检查要剥离的字符串是否是开头,如果是则剪切字符串:

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

推荐阅读