我正在为 Google 快速搜索框开发一个 Python 插件,它对非 ASCII 字符做了一些奇怪的事情。看起来代码工作得很好,直到我尝试构造一个包含非 ASCII 字符的字符串(ü 是我的测试字符)。我使用以下代码片段进行构建,其中 new_task 作为从 GQSB 输入的变量。
the_sig = ("%sapi_key%sauth_token%smethod%sname%sparse%stimeline%s" %
(api_secret, api_key, the_token, method, new_task, doParse, timeline))
它给了我这个错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
我理解正确,这是因为我试图将一个 unicode 字符串在一个 ascii 字符串中。我能找到的所有内容都告诉我在顶部声明编码:
# -*- coding: iso-8859-15 -*-
我有。当我将构建字符串的代码片段拉入新脚本时,它工作得很好。但由于某种原因,在代码其余部分的上下文中,它每次都会失败。我唯一能想到的是,这是因为它在它自己的类中,但这对我来说没有任何意义。
完整代码可以在 GitHub 上找到 here
预先感谢您的帮助。我被这个问题难住了。
最佳答案
您应该采取一些措施来解决此问题。
将所有包含非 ASCII 字符的字符串文字转换为 Unicode 文字。示例:
u'über'
。对 Unicode 进行中间处理。换句话说,如果您收到编码字符串(无论编码如何),请在处理之前将其解码为 Unicode。示例:
s = utf8_string.decode('utf8') + latin1_string.decode('latin1')
输出字符串或将其发送到某个地方时,请使用接收者可以理解的编码对其进行编码。示例:
send(s.encode('utf8'))
。
完整示例:
input1 = get_possibly_nonascii_input().decode('iso-8859-1')
input2 = get_possibly_nonascii_input().decode('iso-8859-1')
input3 = u'üvw'
s = u'%s -> %s' % (input3, (input1 + input2).upper())
send_output(s.encode('utf8'))
关于python - 如何在 python 中正确使用 unicode 字符以避免出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2239017/