In Python, if I have a URL, what is the simplest way to turn something like:
http://stackoverflow.com
into:
<a href="http://stackoverflow.com">http://stackoverflow.com</a>
So far I have tied a lot with Regular Expressions, but nothing works at all.
You could use regex.
>>> import re
>>> s = "http://stackoverflow.com www.foo.com"
>>> re.sub(r'\b((?:https?:\/\/)?(?:www\.)?(?:[^\s.]+\.)+\w{2,4})\b', r'<a href="\1">\1</a>', s)
'<a href="http://stackoverflow.com">http://stackoverflow.com</a> <a href="www.foo.com">www.foo.com</a>'
You can use str.format:
>>> link = 'http://stackoverflow.com'
>>> print('<a href="{0}">{0}</a>'.format(link))
<a href="http://stackoverflow.com">http://stackoverflow.com</a>
>>>
Note however that you need to number the format fields since you are repeating an argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With