Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

python - pprint(): how to use double quotes to display strings?

If I print a dictionary using pprint, it always wraps strings around single quotes ('):

>>> from pprint import pprint
>>> pprint({'AAA': 1, 'BBB': 2, 'CCC': 3})
{'AAA': 1, 'BBB': 2, 'CCC': 3}

Is there any way to tell pprint to use double quotes (") instead? I would like to have the following behaviour:

>>> from pprint import pprint
>>> pprint({'AAA': 1, 'BBB': 2, 'CCC': 3})
{"AAA": 1, "BBB": 2, "CCC": 3}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like you are trying to produce JSON; if so, use the json module:

>>> import json
>>> print json.dumps({'AAA': 1, 'BBB': 2, 'CCC': 3})
{"AAA": 1, "BBB": 2, "CCC": 3}

The pprint() function produces Python representations, not JSON and quoting styles are not configurable. Don’t confuse the two syntaxes. JSON may at first glance look a lot like Python but there are more differences than just quoting styles:

  • JSON is limited to a few specific types only ({...} objects with key-value pairs, [...] arrays, "..." strings, numbers, booleans and nulls). Python data structures are far richer.
  • Python dictionary keys can be any hashable object, JSON object keys can only ever be strings.
  • JSON booleans are written in lowercase,true and false. Python uses title-case, True and False.
  • JSON uses null to signal the absence of a value, Python uses None.
  • JSON strings use UTF-16 codepoints, any non-BMP codepoint is encoded using surrogate pairs. Apart from a handful of single-letter backslash escapes such as and " arbitrary codepoint escapes use uXXXX 16-bit hexadecimal notation. Python 3 strings cover all of Unicode, and the syntax supports xXX, uXXXX, and UXXXXXXXX 8, 16 and 32-bit escape sequences.

If you want to produce indented JSON output (a bit like pprint() outputs indented Python syntax for lists and dictionaries), then add indent=4 and sort_keys=True to the json.dumps() call:

>>> print json.dumps({'AAA': 1, 'CCC': 2, 'BBB': 3}, indent=4, sort_keys=True)
{
    "AAA": 1,
    "BBB": 2,
    "CCC": 3
}

See http://stackoverflow.com/questions/12943819/how-to-python-prettyprint-a-json-file


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...