基本的に、キーと値を文字列化する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
'
}
...しかし、これを行うための組み込みの方法はないようです!
これを行うための標準的/最良の方法が何であるかを知りたいのですが、ない場合はなぜですか? 辞書 (および他のコンテナー) を印刷するときrepr()
ではなく、常に文字列に対して呼び出される特別な理由はありますか?str()