Escaping quotes in string

2019-04-18 15:55发布

问题:

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

回答1:

You need to escape your backslash in the replace in order to get it printed. Try

replace('"','\\"')


回答2:

There's no need to do it the hard way. Let Django serialize the query set for you.



回答3:

I had same problem, I used a python inbuilt escaping method. something like this helped me

[{"pk":"1","name":"John","size":"1/4\" "},{},{},etc]

Ref:-

http://docs.python.org/2/reference/lexical_analysis.html#string-literals



回答4:

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



回答5:

You say:

I have to prepare the list for jQuery

So I assume you are trying to output Python objects in string form into a template file, transformed so that the output string is valid Javascript code.

This is equivalent to serializing them as JSON.

This is a solved problem, instead of replacing single quotes with double quotes etc yourself just do this:

import json

my_python_data = [{'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'}]

str_to_output_in_js_template = json.dumps(my_python_data)

This will handle all the escaping for you and ensure that the result is a valid Javascript object.