How to remove scheme from url in Python?

后端 未结 3 2040
我在风中等你
我在风中等你 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:18

    If you are using these programmatically rather than using a replace, I suggest having urlparse recreate the url without a scheme.

    The ParseResult object is a tuple. So you can create another removing the fields you don't want.

    # py2/3 compatibility
    try:
        from urllib.parse import urlparse, ParseResult
    except ImportError:
        from urlparse import urlparse, ParseResult
    
    
    def strip_scheme(url):
        parsed_result = urlparse(url)
        return ParseResult('', *parsed_result[1:]).geturl()
    

    You can remove any component of the parsedresult by simply replacing the input with an empty string.

    It's important to note there is a functional difference between this answer and @Lukas Graf's answer. The most likely functional difference is that the '//' component of a url isn't technically the scheme, so this answer will preserve it, whereas it will remain here.

    >>> Lukas_strip_scheme('https://yoman/hi?whatup')
    'yoman/hi?whatup'
    >>> strip_scheme('https://yoman/hi?whatup')
    '//yoman/hi?whatup'
    

提交回复
热议问题