UnicodeEncodeError:'charmap' with 'Ö','Ç' etc

UnicodeEncodeError:'charmap' with 'Ö','Ç' etc

我连接到 MySQL 并检索包含“Ö”、“ğ”、“Ş”等的用户名。 它在 MySQL 或 PHP 中工作正常,但在 Python 2.6.8 中,会发生错误。 这是我的代码:

#C:\Python27\Lib\encodings
#-*- coding: utf-8 -*-

conn = MySQLdb.Connect(host="localhost", user="root", passwd="mypass", db="mydb", charset="utf8", init_command="SET NAMES UTF8")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("select * from users");
tmpDict=cursor.fetchallDict()
print tmpDict[0]['NAME'].decode('utf8')

我希望此处显示“Ömer Şirin”,但我收到以下错误:

'ascii' codec can't encode character u'\xd6' in position 0: ordinal not in range(128)

我该如何解决这个问题?

MySQL 驱动程序自动将 UTF-8 字符串解码为 Python Unicode 对象。

你应该能够证明这一点:

>>> type(tmpDict[0]['NAME'])
<type 'unicode'>

您应该能够直接将 tmpDict[0]['NAME'] 打印到控制台。如果您仍然有打印问题,请再次在 Whosebug 中查找异常

两个个错误和两个问题:

  1. UnicodeEncodeError:'charmap' 带有“Ö”、“Ç”等
  2. 'ascii' 编解码器无法对位置 0 中的字符 u'\xd6' 进行编码:序号不在范围内 (128)

如果type(tmpDict[0]['NAME']) == unicode那么第二期很容易重现:

>>> u'\xd6'.decode('utf-8') #XXX BROKEN, DO NOT DO IT!!!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in position 0: ordinal not in range(128)

发生的事情是 u'\xd6' 已经是一个 Unicode 字符串,因此在对其进行解码之前,必须先将其转换为字节,并且 Python 使用默认编码 ('ascii')去做吧。正确的解决方法是drop .decode('utf-8') -- 不解码Unicode字符串(固定在Python 3,如果你尝试解码 Unicode 字符串,你会得到 AttributeError

第一个问题 "UnicodeEncodeError:'charmap'" 可能是由于将 Unicode 打印到 Windows 控制台。要重现,运行 print u'\xd6'。要修复它,install win-unicode-console.