How to remove a path prefix in python?

前端 未结 4 506
走了就别回头了
走了就别回头了 2020-12-28 11:36

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

I want to remove everything before the wa path.

p = path.split(\'/\')
counter         


        
相关标签:
4条回答
  • 2020-12-28 12:02
    import re
    
    path = '/book/html/wa/foo/bar/'
    m = re.match(r'.*(/wa/[a-z/]+)',path)
    print m.group(1)
    
    0 讨论(0)
  • 2020-12-28 12:13
    >>> path = '/book/html/wa/foo/bar/'
    >>> path[path.find('/wa'):]
    '/wa/foo/bar/'
    
    0 讨论(0)
  • 2020-12-28 12:16

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

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

    >>> import os
    >>> full_path = '/book/html/wa/foo/bar/'
    >>> print os.path.relpath(full_path, '/book/html')
    'wa/foo/bar'
    
    0 讨论(0)
  • 2020-12-28 12:16

    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.

    0 讨论(0)
提交回复
热议问题