gpt4 book ai didi

python - 函数 string.lstrip() 在 python 中返回空白字符串

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:55 25 4
gpt4 key购买 nike

在 python 解释器中:'pradeep'.lstrip('prade') 给出了 '' 的输出。我期待这会返回“ep”。为什么这个假设是错误的?

最佳答案

.lstrip() 删除字符集,而不是单词。所有字符 prade以任何顺序,从 pradeep 的开头删除。最后两个字符 ed 仍然是该集合的一部分,也被删除了。如果您使用 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com