我正在尝试缩进 pprint 的输出,以便使用 pprint 获得 8 个空格的缩进。我使用的代码是:
import numpy as np
from pprint import pprint
A = np.array([1, 2, 3, 4])
f = open("log.txt", 'w')
n = 2
for i in range(n):
A = A + 1
f.writelines(list(u' \u27B3 - %s\n'.encode('utf-8') % i for i in A))
pprint(globals())
输出
{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
所需输出
{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
简而言之,在写入文件或使用
pprint
打印时,我需要一个空格缩进。我试过了
pp = pprint.PrettyPrinter(indent=8)
但是不起作用
您无法通过
pprint()
添加额外的前导缩进,不。
pprint.pformat()
函数,然后手动添加缩进:
from pprint import pformat
print ''.join([
' ' + l
for l in pformat(globals()).splitlines(True)])
str.splitlines()
方法 将 pformat()
输出拆分为单独的行,以便于重新连接。
textwrap.indent()
: 来完成缩进
from pprint import pformat
from textwrap import indent
print(indent(pformat(globals()),
' '))
我可能会因为没有直接回答OP限制内的问题而被跳上来,但我建议你在这里使用json库而不是pprint,即:
d = {'dog':7,'cat':{'feet':12,'head':7}}
print(json.dumps(d, indent=2))
屈服
{
"dog": 7,
"cat": {
"feet": 12,
"head": 7
}
}
向 Mahmoud Essam 致敬。
对 Martijn 的答案进行了小幅更新。不需要使用 .format() ,简单的 str concat 就可以了。
from pprint import pformat
def left_indent(text, indent=' ' * 8):
return ''.join([indent + l for l in text.splitlines(True)])
print(indent(pformat(data)))