gareth
gareth

Reputation: 23

How to print in the same format as the python console

I am working with 3D arrays, for example, in an IPython console:

In [8]: xx = [[[0 for i in range(4)] for j in range(4)] for k in range(4)]

xx
Out[9]: 
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

print(xx)
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

When I just evaluate the array in the console it is nicely formatted, but when I print() it, it formats in one long line which then wraps and looks horrible. There are long-winded ways to reproduce the terminal-style formatting from within a program, but is it possible to just call the function that formats for the console directly? I tried

repr(xx)

But that does not have the desired effect. Such a function could be generally useful, not just for arrays.

Upvotes: 2

Views: 69

Answers (1)

U13-Forward
U13-Forward

Reputation: 71620

Use pprint, like the below:

>>> import pprint
>>> pprint.pprint(xx)
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
>>> 

Upvotes: 2

Related Questions