Markup URLs and shorten their label if necessary

import re


CP_URL = re.compile(r'(http://\S+)', re.S)

def markup_url(m):
    """Markup an URL and shorten its label if necessary."""
    url = m.group(1)
    label = url
    if len(label) > 72:
        label = label[:48] + '...' + label[-20:]
    return u'<a href="%s">%s</a>' % (url, label)

text = CP_URL.sub(markup_url, text)