Modify URL components in Python 2

后端 未结 2 1150
星月不相逢
星月不相逢 2021-02-14 10:10

Is there a cleaner way to modify some parts of a URL in Python 2?

For example

http://foo/bar -> http://foo/yah

At present, I\'m doin

2条回答
  •  野性不改
    2021-02-14 11:06

    I guess the proper way to do it is this way.

    As using _replace private methods or variables is not suggested.

    from urlparse import urlparse, urlunparse
    
    res = urlparse('http://www.goog.com:80/this/is/path/;param=paramval?q=val&foo=bar#hash')
    l_res = list(res)
    # this willhave ['http', 'www.goog.com:80', '/this/is/path/', 'param=paramval', 'q=val&foo=bar', 'hash']
    l_res[2] = '/new/path'
    urlunparse(l_res)
    # outputs 'http://www.goog.com:80/new/path;param=paramval?q=val&foo=bar#hash'
    

提交回复
热议问题