Python UnicodeEncodeError: 'ascii' 编解码器无法对位置 0-3 中的字符进行编码:序号不在范围内 (128)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25103575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
提问by yuyb0y
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)
My code is:
我的代码是:
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.
请问我该如何解决这个问题。
Thank you
谢谢
回答by amatellanes
Your file static/users.txtmust contain any non-unicode characters. You must specify any encoding in your program. for intsnace utf-8. You can read more about it here: Unicode HOWTO.
您的文件static/users.txt必须包含任何非 Unicode 字符。您必须在程序中指定任何编码。为intsnace utf-8。您可以在此处阅读更多相关信息:Unicode HOWTO。
回答by abarnert
The problem is that "{}"is non-Unicode str, and you're trying to formata unicodeinto it. Python 2.x handles that by automatically encoding the unicodewith sys.getdefaultencoding(), which is usually 'ascii', but you have some non-ASCII characters.
问题是,"{}"就是非Unicode str,和你想format一unicode进去。Python 2.x 通过自动编码unicodewith 来处理这个问题,sys.getdefaultencoding()通常是'ascii',但是你有一些非 ASCII 字符。
There are two ways to solve this:
有两种方法可以解决这个问题:
Explicitly encode that
unicodein the appropriate character set. For example, if it's UTF-8, do"{}".format(source[1].encode('utf-8')).Use a
unicodeformat string:u"{}".format(source[1]). You may still need toencodethatUserIdlater; I have no idea how yourwrite_filefunction works. But it's generally better to keep everything Unicode as long as possible, only encoding and decoding at the very edges, than to try to mix and match the two.
unicode在适当的字符集中对其进行显式编码。例如,如果它是 UTF-8,请执行"{}".format(source[1].encode('utf-8')).使用
unicode格式字符串:u"{}".format(source[1]). 您可能还需要encode的是UserId更高版本; 我不知道你的write_file函数是如何工作的。但通常最好将所有 Unicode 保留尽可能长,仅在最边缘进行编码和解码,而不是尝试混合和匹配两者。
All that being said, this line of code is useless. "{}".format(foo)converts footo a str, and then formats it into the exact same str. Why?
话虽如此,这行代码是无用的。"{}".format(foo)转换foo为 a str,然后将其格式化为完全相同的str. 为什么?
回答by user3876129
a solution is to set a default encoding to utf-8 instead of ascii in your sitecustomize.py
一种解决方案是在您的 sitecustomize.py 中将默认编码设置为 utf-8 而不是 ascii
回答by philmaweb
Take these functions here when handling strings of unknown encoding:
处理未知编码的字符串时,请在此处使用这些函数:
You want to work with the text?
你想处理文本吗?
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)

