简体   繁体   中英

To print the strings in list inside double quotes

I am creating a list of strings inside double quotes . I am parsing the list to a dictionary where the dictionary is parsed to a json file . the json decoder could not read the strings in list inside single quotes .

>>> number = ["one", "two"]
>>> mapper = {"numbers" : number}

Actual output:

>>> print mapper
{'numbers': ['one', 'two']}

Desired output:

{'numbers': ["one", "two"]}

I am using Python 2.7. Please give an solution. Thanks in advance

You can use json like this.

import json
print json.dumps(array)

Okay. Wow! This is gonna be tricky.

First if you want to generate JSON then use the JSON module . It's going to be far more reliable and handle many corner cases that you're not yet aware of.

Beyond that the thing you have to understand is that this technique of printing a list, like you're doing it, is not really intended for production output. It's a convenience for debugging and pedagogy (learning and teaching).

When you print an object in Python then you're seeing its "representation." Under the hood Python calls __repr__() method as defined by the object's class. This is also how the object is "represented" in the interpreter (when using Python interactively at the >>> prompt).

So, one way you could approach your requirement would be to create your own subclass of Python's list type and over-ride the __repr__() method on that.

Another way would be for you to create your own function (let's call it print_list() ) to print lists in your desired format.

That might look something like:

#!python
def print_list(seq):
    '''print a list in our preferred format'''
    print '[%s]' % ', '.join(['"%s"' % x for x in seq])

In this case we're defining a function which interpolates a string into the string [...]; and that string is defined by joining a sequence of other strings with commas followed by spaces. That sequence of other strings is defined by iterating over our arguments (passed through the seq parameter to our function) and interpolating each of those into a pair of double quotes.

Note that this function would render all objects into double quoted strings. That will NOT match the built-in representational behavior which only puts quotes (the single quotes that you've objected to) around strings. The built-in __repr__ for Python lists will not put quotes around numbers, builtin constants like None and True and False and so on.

Specifically this "interpolation" is done, under the hood, by Python's use of another special method which is called __str__() . For simple data types like strings and numbers this is almost the same as what you see when you print them. For instances there are no quotes around the strings or numbers.

In general it's a bad idea to rely on this sort of implementation detail that's exposed by using an object's representation in your production output formatting.

But the key is you have to understand the distinctions between how data is entered into your code (or the interpreter) ... which is called its "literal" form, how it's represented in some sorts of output (debugging, and in the interpreter), and how it's interpolated. Often the literal form, the representational and string (interpolated) forms will be similar, even identical. Sometimes the won't be.

Addendum to address question in comments:

A variant of the previous function to return the results as a string rather than printing them:

#!python
def list_string(seq):
    '''print a list in our preferred format'''
    return '[%s]' % ', '.join(['"%s"' % x for x in seq])
# Usage example:
rendered = list_string([1, 2, 3, 10])

In fact it's better to write functions render strings into the desired format rather than calling print from within your functions. In general it's best to call print from has high up (towards your __main__ suite) as possible. That makes it easier if you ever have to adapt your program into a module for use with a webUI or a GUI, or to make it work over some custom networking connection or anything of the sort.

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