python - 如何在没有换行符 '\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)
解决方案
我认为在这种情况下,您将不得不遍历字典元素,并将它们打印为键和值
for k,v in d.items():
print('"{0}": {1}'.format(k, v))
推荐阅读
- php - Apache2 php shell_exec 返回与普通用户不同的状态
- azure - 托管在服务结构上的 REST API 的地址
- sql - 为什么计数在分组时不起作用?
- html - 如何在 Boostrap 网格列中使 div 与上面的 div 大小相同?
- android - 如何在画布圈中设置图像视图或图标?
- javascript - 谷歌地图 API。添加标记
- firebase - Firebase,计划函数,如何传递参数/获取本地运行的上下文
- node.js - 如何从 csv 文件 (node.js) 为变量设置值
- validation - 以 Yii2 形式验证输入数组
- jenkins - 此构建是 Jenkins 中缺少的参数化选项