开发者

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

开发者 https://www.devze.com 2023-01-15 21:40 出处:网络
开发者_运维问答Consider: >>> sample = \"hello\'world\" >>> print sample hello\'world
开发者_运维问答

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?


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"


Use:

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

or

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号