python,UnicodeEncodeError,将unicode转换为ascii

Erk*_* M. 0 python unicode python-2.7

首先,我对python很新,所以原谅我所有的n00b东西.所以Python中的应用程序逻辑是这样的:

  1. 我发送和SQL选择到数据库,它返回一个数据数组.
  2. 我需要获取此数据并在另一个SQL插入句子中使用它.

现在问题是,SQL查询返回unicode字符串.select的输出是这样的:

(u'Abc', u'Lololo', u'Fjordk\xe6r')
Run Code Online (Sandbox Code Playgroud)

所以首先我试图将它转换为字符串,但它失败了,因为第三个元素包含这个德语'ae'字母:

for x in data[0]:
    str_data.append(str(x))
Run Code Online (Sandbox Code Playgroud)

我得到:UnicodeEncodeError:'ascii'编解码器不能编码位置6中的字符u'\ xe6':序数不在范围内(128)

当TypeError发生时,我也可以直接插入unicode插入.TypeError:强制转换为Unicode:需要字符串或缓冲区,找到NoneType

有任何想法吗?

Mez*_*man 7

根据我的经验,Python和Unicode通常是个问题.

一般来说,如果你有一个Unicode字符串,你可以将它转换为普通的字符串,如下所示:

normal_string = unicode_string.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

并将普通字符串转换为Unicode字符串,如下所示:

unicode_string = normal_string.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

  • ''utf-8'`通常是正确的选择,但并非总是如此.您应该使用与数据库配置相同的字符集. (2认同)