You can use urlparse.urlparse and the ParseResult._replace method:
>>> import urlparse >>> parsed = urlparse.urlparse("https://www.google.dk:80/barbaz") >>> replaced = parsed._replace(netloc="www.foo.dk:80") >>> print replaced ParseResult(scheme='https', netloc='www.foo.dk:80', path='/barbaz', params='', query='', fragment='')
ParseResult is a subclass of namedtuple and _replace is the namedtuple method, which:
returns a new instance of a named tuple that replaces the specified fields with new values
UPDATE
The port number is used as the @ 2rs2ts attribute in the comment netloc attribute.
Good news: ParseResult has hostname and port attributes. The bad news is: hostname and port are not members of namedtuple , they are dynamic properties, and you cannot do parsed._replace(hostname="www.foo.dk") . This will throw an exception.
If you do not want to break into : and your url always has a port number and does not have username and password (which refers as https: // username: password@www.google.dk: 80 / barbaz ") you can:
parsed._replace(netloc="{}:{}".format(parsed.hostname, parsed.port))
Nigel Tufnel Feb 07 '14 at 13:34 2014-02-07 13:34
source share