如何处理'../'在Python中?

发布于 2024-10-01 18:04:52 字数 194 浏览 1 评论 0原文

我需要从网址中删除 ../something/

例如。从 ../first/bit/of/the/url.html 中剥离 ../first/,其中 first 可以是任何内容。

实现这一目标的最佳方法是什么?

谢谢 :)

i need to strip ../something/ from a url

eg. strip ../first/ from ../first/bit/of/the/url.html where first can be anything.

what's the best way to achieve this?

thanks :)

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

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

发布评论

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

评论(2

眼泪淡了忧伤 2024-10-08 18:04:52

您可以简单地在官方路径分隔符(os.sep,而不是“/”)处分割路径两次并获取最后一位:

>>> s = "../first/bit/of/the/path.html"
>>> s.split(os.sep, 2)[-1]
'bit/of/the/path.html'

这也比分割更有效完全路径并将其重新串在一起。

请注意,当路径包含的路径元素少于 3 个以上时,此代码不会发出错误消息(例如,“file.html”生成“file.html”)。如果您希望代码在路径不符合预期形式时引发异常,则只需询问其第三个元素(对于太短的路径,该元素不存在):

>>> s.split(os.sep, 2)[2]

这可以帮助检测一些细微的错误。

You can simply split the path twice at the official path separator (os.sep, and not '/') and take the last bit:

>>> s = "../first/bit/of/the/path.html"
>>> s.split(os.sep, 2)[-1]
'bit/of/the/path.html'

This is also more efficient than splitting the path completely and stringing it back together.

Note that this code does not complain when the path contains fewer than 3+ path elements (for instance, 'file.html' yields 'file.html'). If you want the code to raise an exception if the path is not of the expected form, you can just ask for its third element (which is not present for paths that are too short):

>>> s.split(os.sep, 2)[2]

This can help detect some subtle errors.

恬淡成诗 2024-10-08 18:04:52

EOL 提供了一种很好且干净的方法,但是我无法抗拒提供正则表达式替代方案:)

>>> import re
>>> m=re.search('^(\.{2}\/\w+/)(.*)
,'../first/bit/of/the/path.html')
>>> m.group(1)
'../first/'

EOL has given a nice and clean approach however I could not resist giving a regex alternative to it:)

>>> import re
>>> m=re.search('^(\.{2}\/\w+/)(.*)
,'../first/bit/of/the/path.html')
>>> m.group(1)
'../first/'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文