Parsing hostname and port from string or url
Question: I can be given a string in any of these formats:

  * url: e.g <http://www.acme.com:456>

  * string: e.g www.acme.com:456, www.acme.com 456, or www.acme.com 

I would like to extract the host and if present a port. If the port value is
not present I would like it to default to 80.

I have tried [urlparse](http://docs.python.org/library/urlparse.html), which
works fine for the url, but not for the other format. When I use urlparse on
hostname:port for example, it puts the hostname in the scheme rather than
netloc.

I would be happy with a solution that uses urlparse and a regex, or a single
regex that could handle both formats.


Answer: You can use urlparse to get hostname from URL string:

    
    
    from urlparse import urlparse
    print urlparse("http://www.website.com/abc/xyz.html").hostname # prints www.website.com
    

