Skip to content Skip to sidebar Skip to footer

Is There A Python Equivalent To The PHP Function Htmlspecialchars()?

Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().

Solution 1:

Closest thing I know about is cgi.escape.


Solution 2:

from django.utils.html import escape
print escape('<div class="q">Q & A</div>')

Solution 3:

Building on @garlon4 answer, you can define your own htmlspecialchars(s):

def htmlspecialchars(text):
    return (
        text.replace("&", "&amp;").
        replace('"', "&quot;").
        replace("<", "&lt;").
        replace(">", "&gt;")
    )

Solution 4:

You probably want xml.sax.saxutils.escape:

from xml.sax.saxutils import escape
escape(unsafe, {'"':'&quot;'}) # ENT_COMPAT
escape(unsafe, {'"':'&quot;', '\'':'&#039;'}) # ENT_QUOTES
escape(unsafe) # ENT_NOQUOTES

Have a look at xml.sax.saxutils.quoteattr, it might be more useful for you


Solution 5:

I think the simplest way is just to use replace:

text.replace("&", "&amp;").replace('"', "&quot;").replace("<", "&lt;").replace(">", "&gt;")

PHP only escapes those four entities with htmlspecialchars. Note that if you have ENT_QUOTES set in PHP, you need to replace quotes with &#039; rather than &quot;.


Post a Comment for "Is There A Python Equivalent To The PHP Function Htmlspecialchars()?"