inserting bracketings into a string

Peter Otten __peter__ at
Thu Nov 18 10:18:47 CET 2004

Still not tested, but should do slightly better than my previous version.
Python 2.4 only:

from operator import itemgetter

def insert_bracketings(text, spans):
    inserts = [(s, "[%s " % r) for (r, s, t) in spans]
    inserts.extend((t, "]") for (r, s, t) in spans)
    inserts.sort(key=itemgetter(0), reverse=True)
    text = list(text)
    for (r, s) in inserts:
        text.insert(r, s)
    return "".join(text)

Apart from cosmetics, this should insert start tags before end tags at the
same position. Relies on all end tags being equal.


More information about the Python-list mailing list