You can parse urls with urlparse , providing a default scheme, and then recombine:
>>> from urlparse import urlparse, urlunparse >>> urlunparse(urlparse('www.example.com', scheme='http')) 'http:///www.example.com'
As I mentioned in my comment, the lack of www not necessarily a mistake.
If you really insist on putting www in the foreground, then:
def fix_url(url): parsed = urlparse('example.com', scheme='http') if parsed.netloc: if not parsed.netloc.startswith('www.'): parsed = parsed._replace(netloc='www.' + parsed.netloc) elif not parsed.path.startswith('www.'): parsed = parsed._replace(path='www.' + parsed.path) return str(parsed) >>> fix_url('http://example.com') 'http:///www.example.com' >>> fix_url('example.com') 'http:///www.example.com'
Peter Wood
source share