在 Python 中操作目录路径
基本上我已经得到了当前的 url 和我想要合并到新 url 中的另一个键,但存在三种不同的情况。
假设当前 url 是 localhost:32401/A/B/foo
如果 key 是 bar 那么我想返回 localhost:32401/A/B/bar
如果 key 以斜杠开头并且是 /A/bar 那么我想返回 localhost :32401/A/bar
最后如果 key 是它自己的独立 url 那么我只想返回该 key = http://foo .com/bar -> http://foo.com/bar
我认为有一种方法可以至少完成前两种情况,而无需手动操作字符串,但 os.path 模块中没有立即出现任何内容。
Basically I've got this current url and this other key that I want to merge into a new url, but there are three different cases.
Suppose the current url is localhost:32401/A/B/foo
if key is bar then I want to return localhost:32401/A/B/bar
if key starts with a slash and is /A/bar then I want to return localhost:32401/A/bar
finally if key is its own independent url then I just want to return that key = http://foo.com/bar -> http://foo.com/bar
I assume there is a way to do at least the first two cases without manipulating the strings manually, but nothing jumped out at me immediately in the os.path module.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您检查过 urlparse 模块吗?
从文档中,
应该可以帮助您解决第一个案例。
显然,您始终可以对其余部分进行基本的字符串操作。
Have you checked out the urlparse module?
From the docs,
Should help with your first case.
Obviously, you can always do basic string manipulation for the rest.
那是因为你想使用
urllib.parse
(对于 Python 3.x)或urlparse
(对于 Python 2.x)。不过,我对此没有太多经验,因此这里有一个使用
str.split()
和str.join()
的代码片段。That's because you want to use
urllib.parse
(for Python 3.x) orurlparse
(for Python 2.x) instead.I don't have much experience with it, though, so here's a snippet using
str.split()
andstr.join()
.Python 中的字符串对象都有startswith 和endswith 方法,应该能够帮助您实现这一点。也许是这样的?
String objects in Python all have startswith and endswith methods that should be able to get you there. Something like this perhaps?