Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn URL into HTML link

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.

like image 555
Progo Avatar asked Jan 19 '26 16:01

Progo


2 Answers

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>'
like image 80
Avinash Raj Avatar answered Jan 21 '26 04:01

Avinash Raj


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!