如何从 Python 中的 url 中删除方案? [英] How to remove scheme from url in Python?

查看:41
本文介绍了如何从 Python 中的 url 中删除方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用 Flask 编写的返回 url 的应用程序.我希望向用户显示的 URL 尽可能干净,所以我想从中删除 http:// .我查看并找到了 urlparse 库,但找不到任何有关如何执行此操作的示例.

I am working with an application that returns urls, written with Flask. I want the URL displayed to the user to be as clean as possible so I want to remove the http:// from it. I looked and found the urlparse library, but couldn't find any examples of how to do this.

最好的方法是什么,如果 urlparse 太过分了,有没有更简单的方法?仅使用常规字符串解析工具从 URL 中删除http://"子字符串是否是不好的做法或导致问题?

What would be the best way to go about it, and if urlparse is overkill is there a simpler way? Would simply removing the "http://" substring from the URL just using the regular string parsing tools be bad practice or cause problems?

推荐答案

我认为 urlparse 没有为此提供单一的方法或函数.这就是我的做法:

I don't think urlparse offers a single method or function for this. This is how I'd do it:

from urlparse import urlparse

url = 'HtTp://stackoverflow.com/questions/tagged/python?page=2'

def strip_scheme(url):
    parsed = urlparse(url)
    scheme = "%s://" % parsed.scheme
    return parsed.geturl().replace(scheme, '', 1)

print strip_scheme(url)

输出:

stackoverflow.com/questions/tagged/python?page=2

如果您(仅)使用简单的字符串解析,则您必须自己处理 http[s] 以及可能的其他方案.此外,这可以处理方案的奇怪大小写.

If you'd use (only) simple string parsing, you'd have to deal with http[s], and possibly other schemes yourself. Also, this handles weird casing of the scheme.

这篇关于如何从 Python 中的 url 中删除方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆