import cgi s = cgi.escape('test".jpg', True)
http://docs.python.org/library/cgi.html#cgi.escape
Note that the True flag indicates that it escapes double quotes. If you need to avoid single quotes (if you are one of those rare people who use single quotes to surround html attributes), read the note in this documentation at xml.sax.saxutils.quoteattr (). The latter does both kinds of quotes, although it is about three times slower:
>>> timeit.Timer( "escape('asdf\"asef', True)", "from cgi import escape").timeit() 1.2772219181060791 >>> timeit.Timer( "quoteattr('asdf\"asef')", "from xml.sax.saxutils import quoteattr").timeit() 3.9785079956054688
source share