I have following code:
# -*- coding: utf-8 -*-
print u"William Burges (1827–81) was an English architect and designer."
当我尝试从命令行运行它时,会出现以下消息:
Traceback (most recent call last):
File "C:\Python27\utf8.py", line 3, in <module>
print u"William Burges (1827ŌĆō81) was an English architect and designer."
File "C:\Python27\lib\encodings\cp775.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position
20: character maps to <undefined>
我该如何解决这个问题,并让Python读取这个\ u2013字符?为什么Python在现有代码中不能读取它,我以为utf-8适用于每个字符。
谢谢
编辑:
此代码打印所需的结果:
# -*- coding: utf-8 -*-
print unicode("William Burges (1827-81) was an English architect and designer.", "utf-8").encode("cp866")
但是当我尝试打印超过一个句子时,例如:
# -*- coding: utf-8 -*-
print unicode("William Burges (1827–81) was an English architect and designer. I am here. ", "utf-8").encode("cp866")
我收到了相同的错误信息:
Traceback (most recent call last):
File "C:\Python27\utf8vs.py", line 3, in <module>
print unicode("William Burges (1827ŌĆō81) was an English architect and desig
ner. I am here. ", "utf-8").encode("cp866")
File "C:\Python27\lib\encodings\cp866.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position
20: character maps to <undefined>
print
已经做的事情,这也是为什么OP会看到编码异常的原因。 - Martijn Pieters