UnicodeDecodeError:“ascii”编解码器无法解码位置8中的字节0xc3:序号不在范围内(128)

2024-04-26 23:42:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这一行得到了这个错误:

logger.debug(u'__call__ with full_name={}, email={}'.format(full_name, email))

为什么?在

name变量的内容是Gonçalves。在


Tags: namedebugformat内容email错误withcall
2条回答

问题是full_name是一个str,而不是unicode对象。在

# -*- coding: UTF-8 -*-
import logging

logging.basicConfig()
logger = logging.getLogger()
logger.warning('testing')

# unicode.format(str) raises an error
name = 'Gonçalves'
print type(name)
print name
try:
    message = u'{}'.format(name)
except UnicodeDecodeError as e:
    print e

# but logger(unicode) is fine
logging.warn(u'Gonçalves')

# so unicode.format(str.decode()) doesn't raise
name = 'Gonçalves'
print type(name)
print name
message = u'{}'.format(name.decode('utf-8'))
logging.warning(message)


# and neither does unicode.format(unicode)
name = u'Gonçalves'
print type(name)
print name
message = u'{}'.format(name)
logging.warning(message)

这样可以解决您的问题:

full_name, email = [unicode(x, 'utf-8') for x in [full_name, email]]

logger.debug(u'__call__ with full_name={}, email={}'.format(full_name, email))

问题是unicode字符串的默认编码是ASCII,它只支持128个字符。使用UTF-8可以解决这个问题。在

免责声明这在细节上可能是错误的,我只在py3中编写代码。在5分钟内学会了这些。在

相关问题 更多 >