views:

999

answers:

6

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().

+3  A: 

try this...

http://docs.python.org/library/htmllib.html#module-htmlentitydefs

Galen
A: 

If you are using django 1.0 then your template variables will already be encoded and ready for display. You also use the safe operator {{ var|safe }} if you don't want it globally turned on.

Paul Tarjan
+2  A: 

Closest thing I know about is cgi.escape.

Karl Guertin
+2  A: 

Hello!

You probably want xml.sax.saxutils.escape:

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

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

NicDumZ
+1  A: 

The html.entities module (htmlentitydefs for python 2.x) contains a dictionary codepoint2name which should do what you need.

>>> import html.entities
>>> html.entities.codepoint2name[ord("&")]
'amp'
>>> html.entities.codepoint2name[ord('"')]
'quot'
sykora
+2  A: 
from django.utils.html import escape
print escape('<div class="q">Q & A</div>')
Agonych
I'm voting for this because I don't want to parse anything like some of the other answers, or even do a search and replace, I want a single function that does it all for me.
paulmorriss