![](/img/trans.png)
[英]Python: sorting the values of a dict and extracting the keys corresponding to the last n values
[英]Best way to print a dict with \n or \t characters in keys or values in python?
本質上,我想打印一個字典,以便它使用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
'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.