python unicode:如何判断字符串是否需要解码为utf-8?

Bin*_*hen 2 python unicode utf-8

我有一个函数接受来自网络的请求.大多数情况下,传入的字符串不是unicode,但有时它是.

我有代码将所有内容转换为unicode,但它报告此错误:

message.create(username, unicode(body, "utf-8"), self.get_room_name(),\
TypeError: decoding Unicode is not supported
Run Code Online (Sandbox Code Playgroud)

我认为原因是'body'参数已经是unicode,所以unicode()引发了异常.

有没有办法避免这种异常,例如在转换之前判断类型?

Len*_*bro 5

  1. 您不能解码为UTF-8,您编码为 UTF-8或解码.
  2. 您可以安全地从UTF8解码,即使它只是ASCII.ASCII是UTF8的子集.
  3. 检测是否需要解码的最简单方法是

    if not isinstance(data, unicode):
        # It's not Unicode!
        data = data.decode('UTF8')
    
    Run Code Online (Sandbox Code Playgroud)