Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 902
blippy Avatar asked Sep 14 '10 10:09

blippy


People also ask

How do you escape a single quote in Python?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

How do I bypass a single quote in JavaScript?

We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

How do you handle a single quote in a string Python?

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ( "'" ) or you can escape it inside single quotes ( '\'' ).

How do you escape a character in Python?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.


1 Answers

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" 
like image 179
Daniel Roseman Avatar answered Oct 05 '22 04:10

Daniel Roseman