I want to convert a string into the standard URL format in Python.
For example:
example.com --> http://example.com
example.com:80 --> http://example.com
example.com:443 --> https://example.com
example.com:8000 --> http://example.com:8000
examplecom --> invalid url
How can I do for it?
Thank you!
CodePudding user response:
I found the solution:
import validators
valid_links() = list()
for link in links: # links is a list of string to test
if str(link).endswith(':80'):
link = 'http://' link[:-3]
elif str(link).endswith(':443'):
link = 'https://' link[:-4]
else:
link = 'http://' link
if validators.url(link):
valid_links.append(link)
CodePudding user response:
Another alternative:
def convert_url(domain):
valid = False
has_port = False
for letter in domain:
if letter == ".":
valid = True
if letter == ":":
has_port = True
if valid:
if has_port:
domain_name, port = domain.split(":")
if port == "80":
return f"http://{domain_name}"
elif port == "443":
return f"https://{domain_name}"
else:
return f"http://{domain_name}:{port}"
else:
return f"http://{domain}"
else:
return "invalid url"
print(convert_url("example.com"))
print(convert_url("example.com:80"))
print(convert_url("example.com:443"))
print(convert_url("example.com:8000"))
print(convert_url("examplecom"))