Changing hostname in a url

url parse
python validate url
python url builder
python get url parameters
python-requests parse url
python strip url parameters
python url basename
python url decode

I am trying to use python to change the hostname in a url, and have been playing around with the urlparse module for a while now without finding a satisfactory solution. As an example, consider the url:

I would like to replace "" with e.g. "", so I get the following url:

So the part I want to replace is what urlparse.urlsplit refers to as hostname. I had hoped that the result of urlsplit would let me make changes, but the resulting type ParseResult doesn't allow me to. If nothing else I can of course reconstruct the new url by appending all the parts together with +, but this would leave me with some quite ugly code with a lot of conditionals to get "://" and ":" in the correct places.

You can use urllib.parse.urlparse function and ParseResult._replace method (Python 3):

>>> import urllib.parse
>>> parsed = urllib.parse.urlparse("")
>>> replaced = parsed._replace(netloc="")
>>> print(replaced)
ParseResult(scheme='https', netloc='', path='/barbaz', params='', query='', fragment='')

If you're using Python 2, then replace urllib.parse with urlparse.

ParseResult is a subclass of namedtuple and _replace is a namedtuple method that:

returns a new instance of the named tuple replacing specified fields with new values


As @2rs2ts said in the comment netloc attribute includes a port number.

Good news: ParseResult has hostname and port attributes. Bad news: hostname and port are not the members of namedtuple, they're dynamic properties and you can't do parsed._replace(hostname=""). It'll throw an exception.

If you don't want to split on : and your url always has a port number and doesn't have username and password (that's urls like "") you can do:

parsed._replace(netloc="{}:{}".format(parsed.hostname, parsed.port))

How to Change the Hostname, URL, or Storage Directory of an , If the hostname of one of your application servers or a load balancing server changes after IBM OpenPages with Watson has been installed, you must perform​  Steps # Steps. Edit the wp-config.php file. After the “define” statements (just before the comment line that says “That’s all, stop editing!”), insert a new line, and type: define Save your wp-config.php file. Open a web browser and manually point it to wp-login.php on the new server. For

You can take advantage of urlsplit and urlunsplit from Python's urlparse:

>>> from urlparse import urlsplit, urlunsplit
>>> url = list(urlsplit(''))
>>> url
['https', '', '/barbaz', '', '']
>>> url[1] = ''
>>> new_url = urlunsplit(url)
>>> new_url

As the docs state, the argument passed to urlunsplit() "can be any five-item iterable", so the above code works as expected.

How to Change the Hostname or URL of an OpenPages Reporting , If the hostname of one of your reporting servers or a load balancing server changes after IBM OpenPages with Watson has been installed, you must perform​  Changing Host Names Remotely. To execute a hostnamectl command on a remote system, use the -H, --host option as follows: ~]# hostnamectl set-hostname -H [username]@hostname. Where hostname is the remote host you want to configure. The username is optional.

Using urlparse and urlunparse methods of urlparse module:

import urlparse

old_url = ''
url_lst = list(urlparse.urlparse(old_url))
# Now url_lst is ['https', '', '/barbaz', '', '', '']
url_lst[1] = ''
# Now url_lst is ['https', '', '/barbaz', '', '', '']
new_url = urlparse.urlunparse(url_lst)



Changing your Workspace Hostname/URL, Changing your Workspace Hostname/URL. Can I update my Workspace host name / url / domain name? Jude Novak avatar. Written by Jude Novak Updated  If you want to change or set hostname of your Linux system, simply run: $ hostname NEW_HOSTNAME Of course, you will need to replace “NEW_HOSTNAME” with the actual hostname that you wish to set. This will change the hostname of your system immediately, but there is one problem – the original hostname will be restored upon next reboot.

A simple string replace of the host in the netloc also works in most cases:

>>> p = urlparse.urlparse('')
>>> p._replace(netloc=p.netloc.replace(p.hostname, '')).geturl()

This will not work if, by some chance, the user name or password matches the hostname. You cannot limit str.replace to replace the last occurrence only, so instead we can use split and join:

>>> p = urlparse.urlparse('')
>>> new_netloc = ''.join(p.netloc.rsplit(p.hostname, 1))
>>> p._replace(netloc=new_netloc).geturl()

Changing the Web Application Server Host Name and Port, In the URL Pattern field, make the appropriate changes and click OK when done. Update FME Server Web URL (For Updating Host Name or Port). On the  Changing the Hostname¶ By default, WSO2 products identify the hostname of the current machine through the Java API. However, this value sometimes yields erroneous results on some environments. Therefore, users are recommended to configure the hostname.

I would recommend also using urlsplit and urlunsplit like @linkyndy's answer, but for Python3 it would be:

>>> from urllib.parse import urlsplit, urlunsplit
>>> url = list(urlsplit(''))
>>> url
['https', '', '/barbaz', '', '']
>>> url[1] = ''
>>> new_url = urlunsplit(url)
>>> new_url

How to Change Destination Hostname of HTTP GET Request Using , This article contains information about using the Uniform Resource Locator (URL​) Transformation feature of a NetScaler appliance to change the destination  Change only the second one that has your current hostname. When you’re done, save, exit, and reboot your computer. Hosts File. The “hosts” file acts sort of like an ultra-simplified DNS server. It’s the file that lets your computer match up a hostname with an IP address on your network. You can find the file at “/etc/hosts.”

What is a Hostname? Meaning, Example & how to check, We explain exactly what it is needed to uncover and how to change it. In the URL, the hostname is www. This is the  The following steps outline how to change the hostname in Ubuntu 18.04. 1. Change the hostname using hostnamectl. In Ubuntu 18.04 we can change the system hostname and related settings using the command hostnamectl.

Change Hostname URL?, I recently taken vps server in GoDaddy. I want to pull my domain when I enter please give approval for this  A Fedora system has a hostname that helps it identify and distinguish itself on a network. Sometimes this name appears as part of a fully qualified domain name (FQDN). A FQDN includes not just the system’s name, but the Internet domain, separated by periods (.). Hostname conventions To be valid, a hostname may only contain letters a-z, numerals 0-9, and dashes (-). An example […]

How do I change my configured site URL?, Change the configuration. Update your url by issuing the ghost config command from inside your Ghost directory: ghost config url To view hostname execute the command: # hostname. To change server hostname execute the following command with preferred hostname value instead of # plesk bin server_pref --update -hostname Restart sw-cp-server and sw-engine services: # service sw-cp-server restart # service sw-engine restart

  • I was trying to avoid any if statements, as it may vary whether the base url has a port number or not. Based on your answers though, it does not seem like I can avoid it :-). Thanks for your help.
  • Note that the hostname is called the netloc and it includes any port numbers. This answer shows that but doesn't make it explicit.
  • Using a private method _replace doesn't feel right.
  • _replace is a part of namedtuple public API. It just starts with the underscore to avoid conflicts with the field names.
  • A heads up - netloc also includes username and password. If you parse something like '' your netloc would be ''.
  • urlparse is not an importable library in pip and as such, this does not work because "import urlparse" does not work.
  • _replace is private, should not be used by client code.
  • Better than accepted answer, especially the second option.
  • @gb: _replace is not private in NamedTuple. It's part of the API:…
  • @Downvoter: Care to mention what you didn't like? A downvote without reason (not obvious) isn't helpful at all. I'd like to improve my answer, if possible.