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

发布于 2024-12-23 18:48:46 字数 316 浏览 2 评论 0原文

我想知道这个的 pythonic 函数是什么:

我想删除 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/'

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/'.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

溇涏 2024-12-30 18:48:46

更好的答案是使用 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'

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'
半窗疏影 2024-12-30 18:48:46

对于 Python 3.4+,您应该使用 pathlib.PurePath.relative_to。
来自文档:

>>> 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'

另请参阅此 StackOverflow 问题您问题的更多答案。

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.

旧故 2024-12-30 18:48:46
>>> path = '/book/html/wa/foo/bar/'
>>> path[path.find('/wa'):]
'/wa/foo/bar/'
>>> path = '/book/html/wa/foo/bar/'
>>> path[path.find('/wa'):]
'/wa/foo/bar/'
猫瑾少女 2024-12-30 18:48:46
import re

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

path = '/book/html/wa/foo/bar/'
m = re.match(r'.*(/wa/[a-z/]+)',path)
print m.group(1)
一枫情书 2024-12-30 18:48:46

Python 3.9 及更高版本中有一个新的字符串函数,称为 .removeprefix 和 .removesuffix。

https://peps.python.org/pep-0616/

这些内置函数行为如下,

def removeprefix(self: str, prefix: str, /) -> str:
    if self.startswith(prefix):
        return self[len(prefix):]
    else:
        return self[:]

def removesuffix(self: str, suffix: str, /) -> str:
    # suffix='' should not call self[:-0].
    if suffix and self.endswith(suffix):
        return self[:-len(suffix)]
    else:
        return self[:]

这不会根据问题直接删除它,但如果您知道完整的前缀,它可能会有所帮助。

There is a new string functions called .removeprefix and .removesuffix in Python 3.9 and later.

https://peps.python.org/pep-0616/

These built-in functions behave like the following

def removeprefix(self: str, prefix: str, /) -> str:
    if self.startswith(prefix):
        return self[len(prefix):]
    else:
        return self[:]

def removesuffix(self: str, suffix: str, /) -> str:
    # suffix='' should not call self[:-0].
    if suffix and self.endswith(suffix):
        return self[:-len(suffix)]
    else:
        return self[:]

this does not directly remove it per the question but if you know the full prefix it can be a help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文