首页 > 解决方案 > 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

标签: python

解决方案


您的代码中的问题是 '%' 的优先级高于条件运算符。因为这,

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

推荐阅读