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?
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.
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.
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 ( '\'' ).
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With