在 python 解释器中: 'pradeep'.lstrip('prade') 给出了 '' 的输出。 我期待这会返回“ep”。 为什么这个假设是错误的?
最佳答案
.lstrip()
删除字符集,而不是单词。所有字符 p
、r
、a
、d
和 e
、以任何顺序,从 pradeep
的开头删除。最后两个字符 e
和 d
仍然是该集合的一部分,也被删除了。如果您使用 .lstrip('drape')
或 .lstrip('adepr')
,您会得到相同的结果。
如果你想从开头删除一个词,使用切片:
example = 'pradeep'
example[5:] if example.startswith('prade') else example
或者,作为一个函数:
def remove_start(inputstring, word_to_remove):
return inputstring[len(word_to_remove):] if inputstring.startswith(word_to_remove) else inputstring
演示:
>>> def remove_start(inputstring, word_to_remove):
... return inputstring[len(word_to_remove):] if inputstring.startswith(word_to_remove) else inputstring
...
>>> remove_start('pradeep', 'prade')
'ep'
关于python - 函数 string.lstrip() 在 python 中返回空白字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20843549/