不支持Python解码Unicode

sim*_*nbs 78 python encoding utf-8 character-encoding

我的Python编码问题.我尝试了不同的方法,但我似乎无法找到将输出编码为UTF-8的最佳方法.

这就是我想要做的:

result = unicode(google.searchGoogle(param), "utf-8").encode("utf-8")
Run Code Online (Sandbox Code Playgroud)

searchGoogle返回第一个Google结果param.

这是我得到的错误:

exceptions.TypeError: decoding Unicode is not supported
Run Code Online (Sandbox Code Playgroud)

有谁知道我如何使用UTF-8编码我的输出Python来避免这个错误?

yak*_*yak 99

看起来google.searchGoogle(param)已经回归unicode:

>>> unicode(u'foo', 'utf-8')

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    unicode(u'foo', 'utf-8')
TypeError: decoding Unicode is not supported
Run Code Online (Sandbox Code Playgroud)

所以你想要的是:

result = google.searchGoogle(param).encode("utf-8")
Run Code Online (Sandbox Code Playgroud)

作为旁注,你的代码希望它返回一个utf-8编码字符串,那么使用相同的编码解码它(使用unicode())和编码返回(使用.encode())的重点是什么?

  • 我希望有一个安全,简单的方法来转换为unicode. (60认同)
  • 老实说,`unicode()`只是在试图理解发生了什么.非常感谢你 :-) (4认同)
  • 现在我有时会得到`ascii'编解码器无法解码位置`的字节0xc3.你知道为什么吗? (2认同)
  • 在我建议的那一行?那么这意味着searchGoogle()返回了一个0xC3字节的字符串.调用`.encode()`会导致Python首先尝试转换为unicode(使用ascii编码).我不知道为什么searchGoogle()有时会返回unicode,有时会返回一个字符串.也许这取决于你在"param"中给出的东西?尽量坚持一种类型. (2认同)