在python中用键或值中的\n或\t字符打印dict的最佳方法?

2024-04-26 00:32:34 发布

您现在位置: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
  '
}

……但我似乎无法用内在的方式来做到这一点!你知道吗

我想知道这样做的标准/最佳方法是什么,如果没有,为什么不呢?打印dict(和其他容器)时,总是在字符串上调用repr()而不是str()有什么特殊原因吗?你知道吗


Tags: 字符串injsonisexampleoutthistb
2条回答

你可以让它更通用,但它可以按原样为\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
'}

更一般的答案是:

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'}

相关问题 更多 >