Search code examples
pythonflaskmarkup

How to turn a Flask Markup string into a normal string


When working with Flask, if you use the escape function, then it will return a Markup string.

This Markup string will automatically turn anything added to it into escaped string.

#message = "Hello <em>World</em>\r\n"
message = escape(message)
#message = u'Hello &lt;em&gt;World&lt;/em&gt;!\r\n'
message = message.replace('\r\n','<br />').replace('\n','<br />')
#message = u'Hello &lt;em&gt;World&lt;/em&gt;!&lt;br /&gt;' Here <br /> is automatically escaped
#But I want message = u'Hello &lt;em&gt;World&lt;/em&gt;!<br />;' 

The new added <br /> is automatically escaped because the escape() return a Markup string.

How to turn this Markup string into a normal python string?


Solution

  • Try to convert to string before replacing:

    message = escape(message)
    message = str(message).replace('\r\n','<br />').replace('\n','<br />')
    

    or to unicode if you have unicode symbols in message:

    message = unicode(message).replace('\r\n','<br />').replace('\n','<br />')