【发布时间】:2018-12-11 18:26:59
【问题描述】:
某个倒霉的同事将一些数据保存到这样的文件中:
s = b'The em dash: \xe2\x80\x94'
with open('foo.txt', 'w') as f:
f.write(str(s))
他们应该在什么时候使用
s = b'The em dash: \xe2\x80\x94'
with open('foo.txt', 'w') as f:
f.write(s.decode())
现在foo.txt 看起来像
b'The em-dash: \xe2\x80\x94'
而不是
The em dash: —
我已经将该文件作为字符串读取:
with open('foo.txt') as f:
bad_foo = f.read()
现在如何将bad_foo 从错误保存的格式转换为正确保存的字符串?
【问题讨论】:
-
.decode没有编码名称就没有意义。无论如何,您为什么首先使用字节字符串?这样做的惯用方法是使用 Unicode 字符串并让 Python 在写入文件时对其进行编码。 -
@tripleee 是别人做的,我的任务是撤消它:)
-
我怀疑没有什么比
eval更有用的建议了。 -
@tripleee 这是一个自我回答。见stackoverflow.com/a/53730411/2954547
-
@shadowtalker 在页面上的“发布您的问题”按钮下方有一个“回答您自己的问题”复选框,让您在比赛前得到答案;-)
标签: python python-3.x unicode character-encoding