Dylanthepiguy
Dylanthepiguy

Reputation: 1731

PrettyPrinter - Print output on separate lines from the start and end bracket

Using something like:

pp = pprint.PrettyPrinter(indent=4, width=...).pprint

Current output of pp(my_list):

[   1,
    2,
    3]

Desired output:

[
    1,
    2,
    3
]

How might this be done?

Upvotes: 2

Views: 1241

Answers (2)

Alcamtar
Alcamtar

Reputation: 1582

You can also postprocess the string:

s = pprint.pformat(obj, indent=4)
s = s[0] + '\n' + s[1:-1] + '\n' + s[-1]
print(s)

This will work for simple lists and dicts, but not nested structures.

The json answer works for native datatypes, but if you have custom classes in your data structure json won't know how to serialize them.

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

Using json module.

Ex:

import json
my_list = [1,2,3]
print(json.dumps(my_list, indent=4))

Output:

[
    1, 
    2, 
    3
]

Upvotes: 4

Related Questions