基本上,我想打印一个字典,使用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
'
}
...但我似乎无法以内置的方式来做到这一点!
我想知道这样做的标准/最佳方法是什么,如果没有,为什么不呢?是否有一个特殊的原因,当打印dicts(和其他容器)时,repr()
总是被调用字符串而不是str()
?
更一般的答案:
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'}
你可以使它更通用,但它适用于\n
和\t
原样
example = {'a\tb': '\nthis\tis\nsome\ttext\n'}
def myPrint(txt):
txt = str(txt)
swaps = [("\\n", "\n"),
("\\t", "\t")]
for swap in swaps:
txt= txt.replace(swap[0], swap[1])
print(txt)
myPrint(example)
{'a b': '
this is
some text
'}