How to remove scheme from url in Python?

后端 未结 3 2076
我在风中等你
我在风中等你 2021-01-12 16:39

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 t

3条回答
  •  醉话见心
    2021-01-12 17:22

    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)
    

    Output:

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

    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.

提交回复
热议问题