Escaping quotes in string

亡梦爱人 提交于 2019-12-04 22:39:55

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

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

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

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!