Python UnicodeEncodeError:&x27;ascii';编解码器可以';t编码位置0-3的字符:序号不在范围内(128)
当我运行代码时,出现以下错误:Python UnicodeEncodeError:&x27;ascii';编解码器可以';t编码位置0-3的字符:序号不在范围内(128),python,python-2.7,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(ADM
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, '')
请问我怎样才能解决这个问题
谢谢您的文件
static/users.txt
必须包含任何非unicode字符。您必须在程序中指定任何编码。对于intsnaceutf-8
。您可以在此处阅读更多信息:。问题是,“{}”是非Unicodestr
,您正试图将格式化为Unicode
。Python2.x通过使用sys.getdefaultencoding()
自动编码unicode
来处理这个问题,它通常是'ascii'
,但是您有一些非ascii字符
有两种方法可以解决此问题:
在适当的字符集中显式地编码unicode
。例如,如果它是UTF-8,则执行“{}”.format(源[1].encode('UTF-8'))
使用unicode
格式字符串:u“{}”。格式(源代码[1])
。以后您可能仍然需要对用户ID
进行编码;我不知道你的write\u文件
函数是如何工作的。但一般来说,最好尽可能长时间地使用Unicode编码,只在边缘进行编码和解码,而不是尝试将两者混合和匹配
尽管如此,这行代码还是没用的“{}”.format(foo)
将foo
转换为str
,然后将其格式化为完全相同的str
。为什么?解决方案是在sitecustomize.py中将默认编码设置为utf-8,而不是ascii
处理未知编码的字符串时,在此处使用以下函数:
你想处理文本吗
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)
这里值得指出的是,这个问题正是Python3.x存在的原因。你确定要学习在旧版本的语言中混合使用Unicode和非Unicode字符串所需的所有笨拙的东西,只是为了在一两年内重新学习所有东西,现在不仅仅是学习更简单、更新的方法?一个字符,它的身份不是通过Unicode表分配的。@amatellanes请检查这个quentionshttp://stackoverflow.com/questions/25088887/nimbuzz-login-config-code-dosnt-work
并帮助我解决问题。@amatellanes:他的文件几乎可以肯定不包含任何非Unicode字符。如果是这样,UTF-8也不会有帮助,因为UTF-8只编码Unicode字符。谢谢。现在,当我使用“{}.format(源代码[1].encode('utf-8'))