This seems like a common task, alter some elements of an array, but my solution didn’t feel very pythonic. Is there a better way to build urls with list comprehension?
links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text)
if len(links) == 0:
return text
urls = []
for link in links:
if link[0:4] == "www.":
link = "http://" + link
urls.append(link)
Maybe something like
links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text)
if len(links) == 0:
return text
urls = map(lambda x : something(x), links)
or
Notes:
("http://"+link if link[0:4]=='www.' else link)– this is ternary operator like ?: in C(link[0:4]=='www.' and "http://"+link or link)– this has the same meaning.On another subject: I would test for http://, not for www. Domains don’t have to start with www. For instance, http://stackoverflow.com.