import re
import urllib.parse

def url_replace_hostname(url_parse_result, hostname):
    userinfo, sep, hostinfo = url_parse_result.netloc.rpartition('@')
    if ':' in hostname:
        hostname = f'[{hostname}]'
    return url_parse_result._replace(netloc=userinfo + sep +
        re.subn(r'\[[^]]*]|[^:]+', hostname, hostinfo, 1)[0])

for url, hostname in (
    ('https://127.0.0.1:6443', 'foo'),
    ('http://u...content-available-to-author-only...r.pass@bar', '1.2.3.4'),
    ('http://user:pass@80:80', '1111:1111:1111:1111:1111'),
    ('http://[fe80::822a:a8ff:fe49:470c%tESt]:1234', 'baz.com')
):
    print(url_replace_hostname(urllib.parse.urlparse(url), hostname).geturl())