1

基本的に、キーと値を文字列化する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()

4

2 に答える 2

1

より一般的な答え:

def myPrint(txt)
    print(bytes(str(txt), 'utf-8').decode("unicode_escape"))

myPrint(example)

{'a b': '
this    is
some    text
'}

これでもう少し遊んでください:

注意ビルトインを上書きすることは一般的に悪い考えであり、これは他の問題を引き起こすかもしれません.

import builtins

def print(*args, literal = False):
        if literal:
            builtins.print(bytes(str(" ".join([str(ag) for ag in args])), 'utf-8').decode("unicode_escape"))
        else:
            builtins.print(*args)

print(example, literal = True)
{'a b': '
this    is
some    text
'}

print(example)
{'a\tb': '\nthis\tis\nsome\ttext\n'}

print(example, literal = False)
{'a\tb': '\nthis\tis\nsome\ttext\n'}
于 2018-09-02T19:31:10.257 に答える