如何在服务器上的 Python 中转义单引号以在客户端的 JavaScript 中使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3708152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape single quotes in Python on a server to be used in JavaScript on a client
提问by rutherford
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.
在我的 Web 应用程序中,我需要存储所有单引号的 Python 字符串,以便稍后在客户端浏览器 JavaScript 中进行操作。问题是 Python 使用了相同的反斜杠转义符号,因此上面详述的替换操作无效。
Is there a simple workaround?
有简单的解决方法吗?
采纳答案by Gintautas Miliauskas
Use:
用:
sample.replace("'", r"\'")
or
或者
sample.replace("'", "\'")
回答by Daniel Roseman
As a general solution for passing data from Python to Javascript, consider serializing it with the jsonlibrary (part of the standard library in Python 2.6+).
作为将数据从 Python 传递到 Javascript 的通用解决方案,请考虑使用json库(Python 2.6+ 中标准库的一部分)对其进行序列化。
>>> sample = "hello'world"
>>> import json
>>> print json.dumps(sample)
"hello\'world"

