擅长:python、mysql、java
<p>问题是Unicode和字节字符串的混合。Python2“有益地”尝试从一个到另一个进行转换,但默认使用<code>ascii</code>编解码器。在</p>
<p>下面是一个例子:</p>
<pre><code>>>> 'aeioü'.replace('a','b') # all byte strings
'beio\xfc'
>>> 'aeioü'.replace(u'a','b') # one Unicode string and it converts...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 4: ordinal not in range(128)
</code></pre>
<p>你提到过从JSON读取UUID。JSON返回Unicode字符串。理想情况下,将所有文本文件解码为Unicode,以Unicode进行所有文本处理,并在写入存储时对文本文件进行编码。在“更大的框架”中,这可能是一个很大的移植工作,但本质上使用<code>io.open</code>和编码来读取文件并解码为Unicode:</p>
^{pr2}$
<p>请注意,<code>encoding</code>应该与您正在读取的文件的实际编码相匹配。这是你必须确定的。在</p>
<p>正如您在编辑中发现的那样,一个快捷方式是将UUID从JSON编码回字节字符串,但目标应该是使用Unicode来处理文本。在</p>
<p>python3在默认情况下通过将字符串设置为Unicode来清理这个过程,并删除与byte/Unicode字符串之间的隐式转换。在</p>