为什么 str.lstrip 去掉一个额外的字符? [英] Why does str.lstrip strip an extra character?
本文介绍了为什么 str.lstrip 去掉一个额外的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望 path.lstrip('/Volumes')
的输出是 '/Users'
解决方案
lstrip
是基于字符的,它从左端删除该字符串中的所有字符.
要验证这一点,请尝试以下操作:
"/Volumes/Users".lstrip("semuloV/") # 也返回 "Users";
由于 /
是字符串的一部分,因此将其删除.
您需要改用切片:
if s.startswith("/Volumes"):s = s[8:]
或者,在 Python 3.9+ 上,您可以使用 removeprefix代码>
:
s = s.removeprefix("/Volumes")
>>> path = "/Volumes/Users"
>>> path.lstrip('/Volume')
's/Users'
>>> path.lstrip('/Volumes')
'Users'
>>>
I expected the output of path.lstrip('/Volumes')
to be '/Users'
解决方案
lstrip
is character-based, it removes all characters from the left end that are in that string.
To verify this, try this:
"/Volumes/Users".lstrip("semuloV/") # also returns "Users"
Since /
is part of the string, it is removed.
You need to use slicing instead:
if s.startswith("/Volumes"):
s = s[8:]
Or, on Python 3.9+ you can use removeprefix
:
s = s.removeprefix("/Volumes")
这篇关于为什么 str.lstrip 去掉一个额外的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文