Escape html in python?

前端 未结 5 729
终归单人心
终归单人心 2021-01-02 23:06

i have a but string might contain \", what should I do to escape it?

Example:

__string__ = t         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 23:09

    import cgi
    s = cgi.escape('test".jpg', True)
    

    http://docs.python.org/library/cgi.html#cgi.escape

    Note that the True flag tells it to escape double quotes. If you need to escape single quotes as well (if you're one of those rare individuals who use single quotes to surround html attributes) read the note in that documentation link about xml.sax.saxutils.quoteattr(). The latter does both kinds of quotes, though it is about three times as slow:

    >>> 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
    

提交回复
热议问题