tags:

views:

242

answers:

3

I have a string where special characters like ' or " or & (...) can appear. How can I convert in the string

string = " Hello "XYZ" this 'is' a test & so on "

automatically every special characters with theire html entities, so that I get this:

string = " Hello "XYZ" this 'is' a test & so on "

Thanks!

+2  A: 

See http://wiki.python.org/moin/EscapingHtml

KennyTM
+1  A: 

The cgi.escape method will convert special charecters to valid html tags

 import cgi
 original_string = 'Hello "XYZ" this \'is\' a test & so on '
 escaped_string = cgi.escape(original_string, True)
 print original_string
 print escaped_string

will result in

Hello "XYZ" this 'is' a test & so on 
Hello "XYZ" this 'is' a test & so on 

The optional second paramter on cgi.escape escapes quotes. By default, they are not escaped

Robert Christie
I don't understand why cgi.escape is so squeamish about converting quotes, and ignores single quotes entirely.
Ned Batchelder
Because quotes do not need to be escaped in PCDATA, they *do* need to be escaped in attributes (which, far more often than not, use double quotes for delimiters), and the former case is far more common than the latter. In general, it's a textbook 90% solution (more like >99%). If you have to save every last byte and want it to dynamically figure out which type of quoting does so, use `xml.sax.saxutils.quoteattr()`.
Mike DeSimone
+1  A: 

A simple string function will do it:

def escape(t):
    """HTML-escape the text in `t`."""
    return (t
        .replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        .replace("'", "&#39;").replace('"', "&quot;")
        )

Other answers in this thread have minor problems: The cgi.escape method for some reason ignores single-quotes, and you need to explicitly ask it to do double-quotes. The wiki page linked does all five, but uses the XML entity &apos;, which isn't an HTML entity.

This code function does all five all the time, using HTML-standard entities.

Ned Batchelder