UnicodeEncodeError:' ascii'编解码器不能对位置0-3中的字符进行编码:序数不在范围内(128)

时间:2014-08-03 10:01:01

标签: python python-2.7

当我运行我的代码时,我收到此错误:

UserId = "{}".format(source[1]) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

我的代码是:

def view_menu(type, source, parameters):
    ADMINFILE = 'static/users.txt'
    fp = open(ADMINFILE, 'r')
    users = ast.literal_eval(fp.read())
    if not parameters:
        if not source[1] in users:
            UserId = "{}".format(source[1])
            users.append(UserId)
            write_file(ADMINFILE,str(users))
            fp.close()
            reply(type, source, u"test")
        else:
            reply(type, source, u"test")

register_command_handler(view_menu, 'test', ['info','muc','all'], 0, '')

请问我如何解决这个问题。

谢谢

4 个答案:

答案 0 :(得分:5)

问题是"{}"是非Unicode str,而您正试图format unicode加入unicode。 Python 2.x通过sys.getdefaultencoding()自动编码'ascii'来处理这个问题,unicode通常是"{}".format(source[1].encode('utf-8')),但你有一些非ASCII字符。

有两种方法可以解决这个问题:

  1. 在相应的字符集中显式编码unicode。例如,如果它是UTF-8,请执行u"{}".format(source[1])

  2. 使用encode格式字符串:UserId。您可能仍然需要write_file以后"{}".format(foo);我不知道你的foo函数是如何工作的。但通常最好尽可能长时间地保留Unicode,只在最边缘进行编码和解码,而不是尝试混合和匹配两者。

  3. 所有这一切,这行代码都没用。 strstr转换为{{1}},然后将其格式化为完全相同的{{1}}。为什么呢?

答案 1 :(得分:5)

在处理未知编码的字符串时,请在此处使用这些函数:

您想使用文字吗?

def read_unicode(text, charset='utf-8'):
    if isinstance(text, basestring):
        if not isinstance(text, unicode):
            text = unicode(obj, charset)
    return text

您希望将文本存储在例如数据库中,请使用:

def write_unicode(text, charset='utf-8'):
    return text.encode(charset)

答案 2 :(得分:0)

解决方案是在sitecustomize.py中将默认编码设置为utf-8而不是ascii

Changing default encoding of Python?

答案 3 :(得分:-2)

您的文件static/users.txt必须包含任何非unicode字符。您必须在程序中指定任何编码。对于intsnace utf-8。您可以在此处详细了解:Unicode HOWTO