Jos*_*osé 3 python string unicode python-2.7
简单地说,以下代码:
f.write(u'Río Negro')
Run Code Online (Sandbox Code Playgroud)
引发以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 1: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我能做什么?
我正在使用Python 2.7.3.
import codecs
with codecs.open('file.txt', 'w', encoding='utf-8') as f:
f.write(u'Río Negro')
Run Code Online (Sandbox Code Playgroud)
在Python 3中,此功能内置于标准open函数中:
with open('file.txt', 'w', encoding='utf-8') as f:
f.write(u'Río Negro')
Run Code Online (Sandbox Code Playgroud)