Amit Tripathi
Amit Tripathi

Reputation: 7261

Python str() double quoted string

I know this question sounds very naive but I am stuck with it. I am using jquery autocomplete and it turns out that it needs ["data1", "data2"] form of list.

I am getting data from a json file and

data = json.load(fobj)['content']
data = [str(data[d]['name']) for d in data.keys()]

['some text', 'some other '....]

but I specifically want a double quoted string in list. I have tried repr(str(data)) but in it gives "'some text'" and then "'some text'".strip("'") but again this returns a single quoted string.

To get the work done i am doing

data = [str(data[d]['name'] + "'") for d in data.keys()]

and later process the "'" at the end of string but this is not the right way.

Is there any way with which i can force str() to return double quoted string something like str(data, quote='"').

Upvotes: 3

Views: 2693

Answers (2)

Mihai Hangiu
Mihai Hangiu

Reputation: 598

In Python single quoted or double quoted strings are the same. For example:

a = 'some text'
b = "some text"

The reason for having both in Python is because you may have:

a2 = 'He said: "Hello!"'
b2 = "It's OK!"

Triple quotes are also used like:

a3 = """some text"""
b3 = '''some text'''

If what you are trying to do is to print somewhere (in a file) a list of double quoted strings, you may do this like this:

lst = ['text 1', 'text 2']
print "[%s]" % ", ".join(map(lambda e: '"%s"' % e, lst))

Output:

["text 1", "text 2"]

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

jQuery means JavaScript. JavaScript literals means JSON. Just re-encode.

>>> json.dumps(['foo', '''bar'''])
'["foo", "bar"]'

Upvotes: 7

Related Questions