views:

56

answers:

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

In my web app I need to store my python string with all single quotes escaped for manipulation later in the client browsers javascript. Trouble is python uses the same backslash escape notation so the replace operation as detailed above has no effect.

Hopefully there is a simple workaround?

+1  A: 

Use:

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

or

sample.replace("'", "\\'")
Gintautas Miliauskas
+3  A: 

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"
Daniel Roseman
+1 this safely takes care of backslashes, newlines and Unicode, which just hacking at the apostrophes won't.
bobince
thanks for this.
rutherford