python - 如何让 python 的 pprint 返回一个字符串而不是打印?

换句话说,什么是 sprintf 等价于 pprint?

最佳答案

pprint模块有一个名为 pformat 的函数,就是为了这个目的。

来自文档:

Return the formatted representation of object as a string. indent, width and depth will be passed to the PrettyPrinter constructor as formatting parameters.

例子:

>>> import pprint
>>> people = [
...     {"first": "Brian", "last": "Kernighan"}, 
...     {"first": "Dennis", "last": "Richie"},
... ]
>>> pprint.pformat(people, indent=4)
"[   {   'first': 'Brian', 'last': 'Kernighan'},\n    {   'first': 'Dennis', 'last': 'Richie'}]"

https://stackoverflow.com/questions/521532/

相关文章:

python - 如何在 Python 中创建对象的副本?

mysql - MySQL 服务器和 MySQL 客户端有什么区别

linux - SIGINT 与 SIGTERM、SIGQUIT 和 SIGKILL 等其他终止信号

linux - 如何使用 strace 跟踪子进程?

python - 使用 IPython 逐步调试

python - Pandas 用空白/空字符串替换 NaN

linux - 如何通过将其内存存储到磁盘并稍后恢复它来在 Linux 中 "hibernate"进

python - 使用 argparse 需要两个参数之一

javascript - 即使没有其他进程阻塞该端口,Node.js 应用程序也无法在端口 80 上

python - 使用 pandas 绘制相关矩阵