I have a python dictionary e.g.:
[{"pk":"1","name":"John","size":"1/4" "},{},{},etc]
That size is 1/4 inch,how would I "escape" that quote? So it still would display it as 1/4",
Its a list of things, so I cant just manually code it like 1/4\"
,
I tried replace('"','\"')
EDIT: The orginal list is a textfield in my Django models:
[{'pk': '91', 'size': '', 'name': 'Thread Flat For BF', 'quantity': '2'}, {'pk': '90', 'size': '', 'name': 'Blade Holders Straight ', 'quantity': '26'},{'size':'3"','name':'2m 1/4" Round bar', 'quantity':'43'},{'size':'5','name':'2m 1/8" Round bar', 'quantity':'4'}]
Next step I have to prepare the list for jQuery, so I replace like this so its in the correct syntax for json. mat_list = manufactured_part.material_list.replace("'",'"')
Then I have this list:
[{"pk": "91", "size": "", "name": "Thread Flat For BF", "quantity": "2"}, {"pk": "90", "size": "", "name": "Blade Holders Straight ", "quantity": "26"},{"size':"3"","name':"2m 1/4" Round bar", "quantity":"43"},{"size":"5","name":"2m 1/8" Round bar", "quantity":"4"}]
So now the list is sent to the template and I loop through it with jquery, but the list is broken because of the " in the strings.
SO...I need to escape those " for the list to work, otherwise it has an obvious syntax error.
Hope this makes sense now.
Thanks
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.
It's done by finishing an already-opened one ( ' ), placing the escaped one ( \' ), and then opening another one ( ' ). It's done by finishing already opened one ( ' ), placing a quote in another quote ( "'" ), and then opening another one ( ' ).
What is "Escaping strings"? Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes: "Hello, World."
The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include: Carriage return and newline: "\r" and "\n" Backslash: "\\"
You need to escape your backslash in the replace in order to get it printed. Try
replace('"','\\"')
Using
shlex.quote("string")
or
pipes.quote("string")
Depending on the python version worked for me.
You can check here more details
https://github.com/python/cpython/blob/master/Lib/shlex.py#L281
There's no need to do it the hard way. Let Django serialize the query set for you.
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