How to escape single quotes in Python on a server to be used in JavaScript on a client

心已入冬 提交于 2019-11-30 12:43:00

问题


Consider:

>>> sample = "hello'world"
>>> print sample
hello'world
>>> print sample.replace("'","\'")
hello'world

In my web application I need to store my Python string with all single quotes escaped for manipulation later in the client browsers JavaScript. The trouble is Python uses the same backslash escape notation, so the replace operation as detailed above has no effect.

Is there a simple workaround?


回答1:


Use:

sample.replace("'", r"\'")

or

sample.replace("'", "\\'")



回答2:


As a general solution for passing data from Python to Javascript, consider serializing it with the json library (part of the standard library in Python 2.6+).

>>> sample = "hello'world"
>>> import json
>>> print json.dumps(sample)
"hello\'world"


来源:https://stackoverflow.com/questions/3708152/how-to-escape-single-quotes-in-python-on-a-server-to-be-used-in-javascript-on-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!