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

标签 python string

在 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/

相关文章:

python - 如何使用 Flask 和 MongoDB 将用户帖子与其 session 链接起来?

python - 从列表中获取元素,循环方式

Python 没有读入正确数量的列

python - 有没有更好的方法来检查输入是否为数字?输入可以是 int 或 float

javascript - 在 Javascript 中是否有一个函数返回给定字符串出现的次数?

c++ - 将字符与 Qt 中的 unicode 进行比较

python - 使用gunicorn运行app报错

python - 如何在 python 中自动最大化 pylab 绘图窗口?

java - 如何使用正则表达式从字符串中删除外部标点符号

java - 给定 2 个字符串,仅删除一位数字以使 1 个字符串按字典顺序更小