rut*_*ord 28 javascript python string escaping
>>> sample = "hello'world"
>>> print sample
hello'world
>>> print sample.replace("'","\'")
hello'world
Run Code Online (Sandbox Code Playgroud)
在我的网络应用程序中,我需要存储我的python字符串,所有单引号都被转义,以便稍后在客户端浏览器javascript中进行操作.麻烦是python使用相同的反斜杠转义表示法,因此上面详述的替换操作无效.
希望有一个简单的解决方法?
Dan*_*man 46
作为将数据从Python传递到Javascript的一般解决方案,请考虑使用json库(Python 2.6+中的标准库的一部分)对其进行序列化.
>>> sample = "hello'world"
>>> import json
>>> print json.dumps(sample)
"hello\'world"
Run Code Online (Sandbox Code Playgroud)
Gin*_*kas 31
使用:
sample.replace("'", r"\'")
Run Code Online (Sandbox Code Playgroud)
要么
sample.replace("'", "\\'")
Run Code Online (Sandbox Code Playgroud)