如何删除Python中的路径前缀?
我想知道这个的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更好的答案是使用 os.path.relpath:
http://docs.python.org/3/library/os.path.html#os.path.relpath
A better answer would be to use os.path.relpath:
http://docs.python.org/3/library/os.path.html#os.path.relpath
对于 Python 3.4+,您应该使用 pathlib.PurePath.relative_to。
来自文档:
另请参阅此 StackOverflow 问题您问题的更多答案。
For Python 3.4+, you should use pathlib.PurePath.relative_to.
From the documentation:
Also see this StackOverflow question for more answers to your question.
Python 3.9 及更高版本中有一个新的字符串函数,称为 .removeprefix 和 .removesuffix。
https://peps.python.org/pep-0616/
这些内置函数行为如下,
这不会根据问题直接删除它,但如果您知道完整的前缀,它可能会有所帮助。
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
this does not directly remove it per the question but if you know the full prefix it can be a help.