Python unicode:为什么在一台机器上工作但在另一台机器上它有时会失败?

Bin*_*hen 4 python unicode python-2.x

我发现python中的unicode真的很麻烦,为什么Python不使用utf-8来表示所有字符串?我在中国所以我必须使用一些无法用ascii表示的中文字符串,我u''用来表示字符串,它在我的ubuntu机器上运行良好,但在另一台ubuntu机器(由linode.com提供的VPS)中,它失败了一些时间.错误是:

UnicodeDecodeError:'ascii'编解码器无法解码位置0中的字节0xe9:序号不在范围内(128)

我使用的代码是:

self.talk(user.record["fullname"] + u"????")
Run Code Online (Sandbox Code Playgroud)

mou*_*uad 12

着名的事情UnicodeDecodeError就是当你像现在一样进行一些字符串操作时:

user.record["fullname"] + u" ????"
Run Code Online (Sandbox Code Playgroud)

因为你正在做的是将str与unicode连接起来,所以python会在执行连接之前对str进行一次隐式强制转换为unicode,这样的强制就像这样:

unicode(user.record["fullname"]) + u" ????"
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         Problem
Run Code Online (Sandbox Code Playgroud)

并且存在问题,因为在执行unicode(something)python时将使用默认编码解码字符串,该编码是python 2中的ASCII.*如果发生您的字符串 user.record["fullname"]有一些非ASCII字符,则会引发着名的UnicodeDecodeError错误.

所以你怎么解决它:

# Decode the str to unicode using the right encoding
# here i used utf-8 because mostly is the right one but maybe it not (another problem!!!)
a = user.record["fullname"].decode('utf-8')

self.talk(a + u" ????")
Run Code Online (Sandbox Code Playgroud)

PS:现在在python 3中,默认编码是utf-8,另外一件事是你不能用字符串连接unicode(python 3中的字节)所以不再有隐式强制