这是确保在utf-8中编码python unicode"string"的最佳方法吗?

mco*_*cot 6 python unicode

从库中的任意"字符串"给出我无法控制,我想确保"字符串"是unicode类型并以utf-8编码.我想知道这是否是最好的方法:

import types

input = <some value from a lib I dont have control over>

if isinstance(input, types.StringType):
    input = input.decode("utf-8")
elif isinstance(input, types.UnicodeType):
    input = input.encode("utf-8").decode("utf-8")
Run Code Online (Sandbox Code Playgroud)

在我的实际代码中,我将其包装在try/except中并处理错误,但我将该部分删除了.

jd.*_*jd. 5

Unicode对象未编码(它在内部,但作为Python用户,这应该是透明的).该行input.encode("utf-8").decode("utf-8")没有多大意义:您在开头的末尾获得完全相同的Unicode字符序列.

if isinstance(input, str):
    input = input.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

您需要确保将str对象(字节字符串)转换为Unicode字符串.