A good way to escape quotes in a database query string?

后端 未结 9 1245
暖寄归人
暖寄归人 2020-12-09 07:49

I\'ve tried all manner of Python modules and they either escape too much or in the wrong way. What\'s the best way you\'ve found to escape quotes (\", \') in Python?

9条回答
  •  庸人自扰
    2020-12-09 08:33

    The easy and standard way to escape strings, and convert other objects to programmatic form, is to use the built in repr() function. It converts an object into the representation you would need to enter it with manual code.

    E.g.:

    s = "I'm happy I am \"here\" now"
    print repr(s)
    >>  'I\'m happy I am "here" now'
    

    No weird hacks, it's built in and it just works for most purposes.

提交回复
热议问题