本质上,我想打印一个字典,这样它就可以使用str()
而不是repr()
来字符串化它的键和值。你知道吗
在某些json中保存回溯字符串时,这将特别有用。但这似乎比我想象的要困难得多:
In [1]: import pprint, json
In [2]: example = {'a\tb': '\nthis\tis\nsome\ttext\n'}
In [3]: print(example)
{'a\tb': '\nthis\tis\nsome\ttext\n'}
In [4]: str(example)
Out[4]: "{'a\\tb': '\\nthis\\tis\\nsome\\ttext\\n'}"
In [5]: pprint.pprint(example)
{'a\tb': '\nthis\tis\nsome\ttext\n'}
In [6]: pprint.pformat(example)
Out[6]: "{'a\\tb': '\\nthis\\tis\\nsome\\ttext\\n'}"
In [7]: json.dumps(example, indent=2)
Out[7]: '{\n "a\\tb": "\\nthis\\tis\\nsome\\ttext\\n"\n}'
In [8]: print(json.dumps(example, indent=2))
{
"a\tb": "\nthis\tis\nsome\ttext\n"
}
我想要(和期望)的行为是:
> print(d)
{'a b': '
this is
some text
'}
> pprint.pprint(d)
{
'a b': '
this is
some text
'
}
或者,如果pprint真的很聪明:
> pprint.pprint(d)
{
'a b': '
this is
some text
'
}
……但我似乎无法用内在的方式来做到这一点!你知道吗
我想知道这样做的标准/最佳方法是什么,如果没有,为什么不呢?打印dict(和其他容器)时,总是在字符串上调用repr()
而不是str()
有什么特殊原因吗?你知道吗
你可以让它更通用,但它可以按原样为
\n
和\t
工作更一般的答案是:
再玩一点:
注意覆盖内置通常是个坏主意,这可能会导致其他问题,但是。。。。。。。你知道吗
相关问题 更多 >
编程相关推荐