How to remove a path prefix in python?

PythonStringPathPrefix

Python Problem Overview


I wanted to know what is the pythonic function for this :

I want to remove everything before the wa path.

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

For instance, I want '/book/html/wa/foo/bar/' to become '/wa/foo/bar/'.

Python Solutions


Solution 1 - Python

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'

Solution 2 - Python

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.

Solution 3 - Python

>>> path = '/book/html/wa/foo/bar/'
>>> path[path.find('/wa'):]
'/wa/foo/bar/'

Solution 4 - Python

import re

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNatimView Question on Stackoverflow
Solution 1 - PythonMitch ミッチView Answer on Stackoverflow
Solution 2 - PythonpjgranahanView Answer on Stackoverflow
Solution 3 - PythonFelix LoetherView Answer on Stackoverflow
Solution 4 - PythonvivekView Answer on Stackoverflow