【发布时间】:2018-09-17 01:30:00
【问题描述】:
我正在尝试编写一个可以通过 python 2 和 3 运行的程序。它从网站读取字符并写入文件。我已经从 __future__ 导入了unicode_literals。
直接尝试编写如下所示的字符串:
txt = u'his$\u2026\n'
会导致UnicodeEncodeError:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 4: ordinal not in range(128)
在python2中将其写入文件的唯一方法是:
fp = open("/tmp/test", "w")
txt2 = txt.encode('utf-8')
fp.write(txt2) # It works
type(txt2) # str - that is why it works
但是,尝试在 python3 中重用相同的代码是行不通的,因为在 python 3 中,
type(txt2) # is byte type
例如
txt.encode('utf-8')
b'his$\xe2\x80\xa6\n'
强制 fp.write(txt2) 会抛出 TypeError:
TypeError: write() argument must be str, not bytes
所以,可以在 python 2 和 3 中使用相同的代码块将txt = u'his$\u2026\n' 写入文件中。(除了在 fp.write 上使用包装器)
【问题讨论】:
-
使用 'print(txt.encode('utf-8'), file=fp)` 是兼职解决方案。它将在 python2 中运行良好。但是,它在 python3 中运行得不够好,它不会打印实际字符,而是实际打印字节的字符串文字表示。如,而不是打印 his$... python3 将结束: b'his$\xe2\x80\xa6\n'。
-
“混合字符串”是什么意思?我看到你已经标记了这个 unicode-normalization;这是一个问题吗?
-
我不应该说混合字符串,我的错。打印时的字符串如下所示:his$...
标签: python python-unicode python-2to3