title: Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?
body: <p>For instance, say I wanted a function to escape a string for use in HTML (as in Django's <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape" rel="noreferrer">escape filter</a>):</p>
  
  <pre><code>    def escape(string):
          """
          Returns the given string with ampersands, quotes and angle 
          brackets encoded.
          """
          return string.replace('&amp;', '&amp;amp;').replace('&lt;', '&amp;lt;').replace('&gt;', '&amp;gt;').replace("'", '&amp;#39;').replace('"', '&amp;quot;')
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>    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;', '&amp;amp;'),
                               {'&lt;': '&amp;lt;', '&gt;': '&amp;gt;', 
                                "'": '&amp;#39;', '"': '&amp;quot;'})
  </code></pre>
  
  <p>Does such a function exist, or is the standard Python idiom to use what I wrote before?</p>