我正在撰寫一些需要同時使用 Py2.7 和 Py3.7 的代碼。
我需要使用 UTF-8 編碼將文本寫入檔案。我的代碼如下所示:
import six
...
content = ...
if isinstance(content, six.string_types):
content = content.encode(encoding='utf-8', errors='strict')
# write 'content' to file
以上,是否可以從 Py2.7 或 Py3.7 加注content.encode()?UnicodeError我想不出一個可行的方案。我不是 Python 專家,所以我認為一定有一個極端情況。
這是我認為它永遠不會提高的原因UnicodeError:
six.string_types涵蓋三種型別:Py2.7str&unicode, Py3.7str- 所有這些型別總是可以編碼為 UTF-8。
uj5u.com熱心網友回復:
是的,有可能:
import six
content = ''.join(map(chr, range(0x110000)))
if isinstance(content, six.string_types):
content = content.encode(encoding='utf-8', errors='strict')
結果(在線試用!,使用 Python 3.7.4):
Traceback (most recent call last):
File ".code.tio", line 5, in <module>
content = content.encode(encoding='utf-8', errors='strict')
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 55296-57343: surrogates not allowed
UnicodeEncodeErrors 是UnicodeErrors 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452169.html
標籤:Python python-3.x python-2.7 python-unicode
上一篇:Python-從一個串列切換到另一個串列(最佳方式)
下一篇:如何用檔案中的空格替換換行符?
