Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?
- by meeselet
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('&', '&').replace('<', '<').replace('>', '>').replace("'", ''').replace('"', '"')
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('&', '&'),
{'<': '<', '>': '>', "'": ''', '"': '"'})
Does such a function exist, or is the standard Python idiom to use what I wrote before?