Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> path = "/Volumes/Users"
>>> path.lstrip('/Volume')
's/Users'
>>> path.lstrip('/Volumes')
'Users'
>>>
Run Code Online (Sandbox Code Playgroud)
我期待输出path.lstrip('/Volumes')应该是/Users
ang*_*son 25
lstrip 是基于字符的,它会删除该字符串中左端的所有字符.
要验证这一点,试试这个:
"/Volumes/Users".lstrip("semuloV/")
Run Code Online (Sandbox Code Playgroud)
由于/是字符串的一部分,因此将其删除.
我怀疑你需要使用切片代替:
if s.startsWith("/Volumes"):
s = s[8:]
Run Code Online (Sandbox Code Playgroud)
但希望对Python库有更深入了解的人可能会给你一个更好的选择.
Nad*_*mli 17
Strip是基于字符的.如果您尝试进行路径操作,则应该查看os.path
>>> os.path.split("/Volumes/Users")
('/Volumes', 'Users')
Run Code Online (Sandbox Code Playgroud)
tue*_*ist 14
传递给的参数lstrip被视为一组字符!
>>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
Run Code Online (Sandbox Code Playgroud)
另请参阅文档
您可能想要使用str.replace()
str.replace(old, new[, count])
# e.g.
'/Volumes/Home'.replace('/Volumes', '' ,1)
Run Code Online (Sandbox Code Playgroud)
返回字符串的副本,其中所有出现的substring old都替换为new.如果给出可选参数计数,则仅替换第一次计数.
对于路径,您可能想要使用os.path.split().它返回路径元素的列表.
>>> os.path.split('/home/user')
('/home', '/user')
Run Code Online (Sandbox Code Playgroud)
对你的问题:
>>> path = "/vol/volume"
>>> path.lstrip('/vol')
'ume'
Run Code Online (Sandbox Code Playgroud)
上面的例子显示了如何lstrip()工作.它从左边开始删除'/ vol'.然后,再次启动...因此,在您的示例中,它完全删除了"/ Volumes"并开始删除"/".它只删除了'/',因为此斜杠后面没有'V'.
HTH