Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?

Posted by meeselet on Stack Overflow See other posts from Stack Overflow or by meeselet
Published on 2010-03-20T18:11:12Z Indexed on 2010/03/20 18:21 UTC
Read the original article Hit count: 271

For instance, say I wanted a function to escape a string for use in HTML (as in Django's escape filter):

    def escape(string):
    """
    Returns the given string with ampersands, quotes and angle brackets encoded.
    """        return string.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace("'", '&#39;').replace('"', '&quot;')

This works, but it gets ugly quickly and appears to have poor algorithmic performance (in this example, the string is repeatedly traversed 5 times). What would be better is something like this:

    def escape(string):
    """
    Returns the given string with ampersands, quotes and angle brackets encoded.
    """
    # Note that ampersands must be escaped first; the rest can be escaped in 
    # any order.
    return replace_multi(string.replace('&', '&amp;'),
                         {'<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;'})

Does such a function exist, or is the standard Python idiom to use what I wrote before?

© Stack Overflow or respective owner

Related posts about python

Related posts about search-and-replace