python - python数据类型覆盖在打印和写入中表现不同
问题描述
代码片段如下,(如果某些键不在字典中,我想存储整个字典内容,否则只存储键的值)
result = {
'stdout': 'some output'
}
print('result: %s' % result['stderr'] if 'stderr' in result else result)
with open('result.txt', 'w') as f:
f.write('result: %s\n' % result['stderr'] if 'stderr' in result else result)
在这里,我尝试记录一些消息使用write
,检查是否stderr
在 dictresult
中,如果是则使用它(一个字符串),否则记录 dict result
。
它工作正常,print
但失败了write
:
TypeError: write() 参数必须是 str,而不是 dict
因为我使用%s
我希望字符串或字典会自动转换为字符串?(即str(result)
)
为什么它失败了write
?
解决方案
您的代码中的问题是 '%' 的优先级高于条件运算符。因为这,
'result: %s' % result['stderr'] if 'stderr' in result else result
相当于
('result: %s' % result['stderr']) if 'stderr' in result else result
所以,如果'stderr' not in result
,这个表达式将返回result
,它是一个字典。现在,print()
将打印任何内容,但write
需要一个字符串参数,并且在接收到 dict 时会失败。
你想要的结果是:
'result: %s' % (result['stderr'] if 'stderr' in result else result)
您的代码应修改如下:
print('result: %s' % (result['stderr'] if 'stderr' in result else result))
with open('result.txt', 'w') as f:
f.write('result: %s\n' % (result['stderr'] if 'stderr' in result else result))
推荐阅读
- ibm-watson - 使用的 Watson 辅助算法
- opencl - 仅对 OpenCL 内核中的缓冲区子集进行操作
- java - for 循环中的 JSONArray.add(JSONObject) 正在替换 for 循环中的旧值,并且 Array 包含循环中的最后一个值
- node.js - 无法在 Windows 上使用电子 4.0.6 加载一些本机节点 js 模块
- c - 静态库中函数调用中的多个符号
- rx-java - 使用 RxJava 时如何在 couchbase 中找到不可用的实体?
- javascript - java脚本中的“作用域链”是指针吗?
- mysql - SQL:计算一个类别中不同项目的总数
- api - 使用 Tibco BW Vers6 调用外部 API
- amazon-cognito - 用户的会话无效,会话已过期