如何删除 Python 中的路径前缀?

我想知道 Python 的功能是什么:

我想删除 wa路径之前的所有内容。

p = path.split('/')
counter = 0
while True:
if p[counter] == 'wa':
break
counter += 1
path = '/'+'/'.join(p[counter:])

例如,我希望 '/book/html/wa/foo/bar/'变成 '/wa/foo/bar/'

76214 次浏览
>>> path = '/book/html/wa/foo/bar/'
>>> path[path.find('/wa'):]
'/wa/foo/bar/'
import re


path = '/book/html/wa/foo/bar/'
m = re.match(r'.*(/wa/[a-z/]+)',path)
print m.group(1)

A better answer would be to use os.path.relpath:

http://docs.python.org/3/library/os.path.html#os.path.relpath

>>> import os
>>> full_path = '/book/html/wa/foo/bar/'
>>> relative_path = '/book/html'
>>> print(os.path.relpath(full_path, relative_path))
'wa/foo/bar'

For Python 3.4+, you should use pathlib.PurePath.relative_to. From the documentation:

>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')


>>> p.relative_to('/etc')
PurePosixPath('passwd')


>>> p.relative_to('/usr')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pathlib.py", line 694, in relative_to
.format(str(self), str(formatted)))
ValueError: '/etc/passwd' does not start with '/usr'

Also see this StackOverflow question for more answers to your question.