首页 > 解决方案 > 如何在没有换行符 '\n' 字符的情况下打印字典值?

问题描述

假设这是我的字典。

d = {"id": 12345, "msg": "Some msgs \n from the \n text file"}

我想将这本字典打印为:

>>> print(d)
{
"id": 12345,
"msg": "Some msgs
        from the
        text file"
}

我怎样才能做到这一点?

另外,我无法将带有换行符的字符串返回到格式化的字符串中。假设下面是我的字符串:

str = "Some msgs \n from the \n text file"

在打印它时,我会得到格式化的字符串:

>>> print(str)
Some msgs
from the
text file

但是我怎样才能使下面的代码类似于打印格式化字典?

d["msg"] = str
print(d)

标签: pythondictionary

解决方案


我认为在这种情况下,您将不得不遍历字典元素,并将它们打印为键和值

for k,v in d.items():
    print('"{0}": {1}'.format(k, v))

推荐阅读