简体   繁体   中英

How to print out a list of empty strings of size n represented by double quotes in python2

How to print out a list of empty strings of size n while the empty strings are represented by double quotes "" not single quotes '' ( ["", "", ""] ) in python2?

I want to initialize a list of ["", "", "", ""] not a list of ['', '', '', ''] of a given size n, it has nothing to do with JSON format.

And why does python automatically convert all the double quotes into single quotes?
ie print ["abc"] will print out ['abc'] and print [""] will print out ['']

So far I can only get single quotes printed out [''] but the output I'm seeking strictly requires double quotes [""] inside and how to do that?

print [""] will print out ['']

print [`""`] will print out ["''"]

print ['""'] will print out ['""']

How you represent your data in code is not part of that data itself . That is, "foo" and 'foo' and r'foo' are all the exact same string . There's no semantic difference between them (after parsing, the way they're stored in memory is identical), so they get printed the same way.

If you want to print something in JSON syntax (and double quotes are the only type valid for strings in JSON), use json.dumps() to generate a JSON encoding of your list (and its enclosed string). This will necessarily use double quotes, because if it didn't use double quotes, the result would not be valid JSON.

That is:

import json

a = ['']
print(json.dumps(a))

...will have your intended result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM