UnicodeEncodeError: 'ascii' 编解码器无法对位置 0-3 中的字符进行编码:序号不在范围内 (128) [英] UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

查看:99
本文介绍了UnicodeEncodeError: 'ascii' 编解码器无法对位置 0-3 中的字符进行编码:序号不在范围内 (128)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行我的代码时出现此错误:

when i run my code i get this error:

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, '')

请问我该如何解决这个问题.

Please how i can solve this problem.

谢谢

推荐答案

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

Take these functions here when handling strings of unknown encoding:

您想处理文本吗?

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

你想存储文本,例如在数据库中,使用这个:

You want to store the text, for example in a database, use this:

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

这篇关于UnicodeEncodeError: 'ascii' 编解码器无法对位置 0-3 中的字符进行编码:序号不在范围内 (128)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆