How can I prepend http to a url if it doesn't begin with http?

前端 未结 4 1636
陌清茗
陌清茗 2021-01-08 00:21

I have urls formatted as:

google.com
www.google.com
http://google.com
http://www.google.com

I would like to convert all type of links to a

4条回答
  •  半阙折子戏
    2021-01-08 00:43

    For the formats that you mention in your question, you can do something as simple as:

    def convert(url):
        if url.startswith('http://www.'):
            return 'http://' + url[len('http://www.'):]
        if url.startswith('www.'):
            return 'http://' + url[len('www.'):]
        if not url.startswith('http://'):
            return 'http://' + url
        return url
    

    But please note that there are probably other formats that you are not anticipating. In addition, keep in mind that the output URL (according to your definitions) will not necessarily be a valid one (i.e., the DNS will not be able to translate it into a valid IP address).

提交回复
热议问题