当我运行我的代码时,我收到此错误:
UserId = "{}".format(source[1]) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我的代码是:
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, '')
Run Code Online (Sandbox Code Playgroud)
请问我该如何解决这个问题.
谢谢
问题是,"{}"
就是非Unicode str
,和你想format
一unicode
进去.Python 2.x通过自动编码unicode
with来处理它,sys.getdefaultencoding()
通常是'ascii'
,但你有一些非ASCII字符.
有两种方法可以解决这个问题:
unicode
在适当的字符集中显式编码.例如,如果它是UTF-8,那么"{}".format(source[1].encode('utf-8'))
.
使用unicode
格式字符串:u"{}".format(source[1])
.您可能还需要encode
的是UserId
更高版本; 我不知道你的write_file
功能是如何工作的.但通常最好尽可能长时间地保留Unicode,只在最边缘进行编码和解码,而不是尝试混合和匹配两者.
话虽如此,这行代码是没用的."{}".format(foo)
转换foo
为a str
,然后将其格式化为完全相同的str
.为什么?
在处理未知编码的字符串时,请执行以下函数:
你想使用文本吗?
def read_unicode(text, charset='utf-8'):
if isinstance(text, basestring):
if not isinstance(text, unicode):
text = unicode(obj, charset)
return text
Run Code Online (Sandbox Code Playgroud)
您想要存储文本,例如在数据库中,使用:
def write_unicode(text, charset='utf-8'):
return text.encode(charset)
Run Code Online (Sandbox Code Playgroud)
ama*_*nes -2
您的文件static/users.txt
必须包含任何非 unicode 字符。您必须在程序中指定任何编码。对于 intsnace utf-8
。您可以在这里阅读更多相关信息:Unicode HOWTO。