【发布时间】:2010-12-13 19:36:20
【问题描述】:
>>> path = "/Volumes/Users"
>>> path.lstrip('/Volume')
's/Users'
>>> path.lstrip('/Volumes')
'Users'
>>>
我希望path.lstrip('/Volumes') 的输出是'/Users'
【问题讨论】:
>>> path = "/Volumes/Users"
>>> path.lstrip('/Volume')
's/Users'
>>> path.lstrip('/Volumes')
'Users'
>>>
我希望path.lstrip('/Volumes') 的输出是'/Users'
【问题讨论】:
lstrip 是基于字符的,它从左端删除该字符串中的所有字符。
要验证这一点,试试这个:
"/Volumes/Users".lstrip("semuloV/") # also returns "Users"
由于/ 是字符串的一部分,因此将其删除。
您需要改用切片:
if s.startswith("/Volumes"):
s = s[8:]
或者,在 Python 3.9+ 上,您可以使用 removeprefix:
s = s.removeprefix("/Volumes")
【讨论】:
path = "/Volumes/Users" drive = "/Volumes" if path.startswith(drive): path = path.split(drive, 1)[1]
传递给lstrip 的参数被视为一组字符!
>>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
另请参阅documentation
你可能想使用 str.replace()
str.replace(old, new[, count])
# e.g.
'/Volumes/Home'.replace('/Volumes', '' ,1)
返回字符串的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 count,则仅替换第一个 count 出现。
对于路径,您可能需要使用os.path.split()。它返回路径元素的列表。
>>> os.path.split('/home/user')
('/home', '/user')
你的问题:
>>> path = "/vol/volume"
>>> path.lstrip('/vol')
'ume'
上面的例子展示了lstrip() 的工作原理。它删除了左侧的“/vol”起始形式。然后,又开始了……
因此,在您的示例中,它完全删除了“/Volumes”并开始删除“/”。它只删除了“/”,因为这个斜线后面没有“V”。
HTH
【讨论】:
'/home/user/Volumes/important_path'.replace('/Volumes', '', 1) --> '/home/user/important_path'
'/home/user/Volumes_for_my_mp3s/jazz'.replace('/Volumes', '', 1) --> '/home/user_for_my_mp3s/jazz'。看看你还缺少什么? :)
lstrip 文档说:
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
因此,您将删除给定字符串中包含的每个字符,包括“s”和“/”字符。
【讨论】:
这是一个原始版本的 lstrip(我写的),它可能会帮助你理清思路:
def lstrip(s, chars):
for i in range len(s):
char = s[i]
if not char in chars:
return s[i:]
else:
return lstrip(s[i:], chars)
因此,您可以看到每次出现在 chars 中的字符都被删除,直到遇到不在 chars 中的字符。一旦发生这种情况,删除就会停止,字符串的其余部分会被简单地返回
【讨论】: