37

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?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
blippy
  • 9,438
  • 13
  • 48
  • 70

2 Answers2

59

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
  • 567,968
  • 59
  • 825
  • 842
43

Use:

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

or

sample.replace("'", "\\'")
Gintautas Miliauskas
  • 7,416
  • 4
  • 31
  • 34