Question

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?

Was it helpful?

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 />')

OTHER TIPS

Are you looking for message.unescape()?

EDIT: Reading your question again more carefully, I think I know understand your issue.

You need to convert your Markup object back into a str before you call its replace method for it to not auto-escape anymore, like so:

str(message).replace(foo, bar)

Then if you DO need to still have a Markup object you can convert it back.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top