Working With Safe Text

markupsafe.escape(s) → markup

Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.

class markupsafe.Markup

A string that is ready to be safely inserted into an HTML or XML document, either because it was escaped or because it was marked safe.

Passing an object to the constructor converts it to text and wraps it to mark it safe without escaping. To escape the text, use the escape() class method instead.

>>> Markup('Hello, <em>World</em>!')
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape('Hello, <em>World</em>!')
Markup('Hello &lt;em&gt;World&lt;/em&gt;!')

This implements the __html__() interface that some frameworks use. Passing an object that implements __html__() will wrap the output of that method, marking it safe.

>>> class Foo:
...     def __html__(self):
...         return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')

This is a subclass of the text type (str in Python 3, unicode in Python 2). It has the same methods as that type, but all methods escape their arguments and return a Markup instance.

>>> Markup('<em>%s</em>') % 'foo & bar'
Markup('<em>foo &amp; bar</em>')
>>> Markup('<em>Hello</em> ') + '<foo>'
Markup('<em>Hello</em> &lt;foo&gt;')
classmethod escape(s)

Escape a string. Calls escape() and ensures that for subclasses the correct type is returned.

striptags()

unescape() the markup, remove tags, and normalize whitespace to single spaces.

>>> Markup('Main &raquo;        <em>About</em>').striptags()
'Main » About'
unescape()

Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent.

>>> Markup('Main &raquo; <em>About</em>').unescape()
'Main » <em>About</em>'

Optional Values

markupsafe.escape_silent(s) → markup

Like escape but converts None to an empty string.

Convert an Object to a String

markupsafe.soft_unicode(object) → string

Make a string unicode if it isn’t already. That way a markup string is not converted back to unicode.