将变量类型转换为unicode字符串

fra*_*jwu 5 python unicode int encoding utf-8

我正在寻找一种将变量(可以是ASCII字符串,带有é或£等额外字符的unicode字符串,或浮点数或整数)转换为unicode字符串的方法。

variable.encode('utf-8')哪里variable是整数导致AttributeError: 'int' object has no attribute 'encode'

str(variable).encode('utf-8')variable字符串'£'在哪里UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

有没有一种简单的方法可以完成我在Python 2.7中寻找的工作?还是我必须检查变量的类型并以不同的方式处理它?

Mar*_*ers 4

编码永远不会产生unicode对象。您从字节解码unicode为.

因此,您可以通过解码转换为str(字节字符串)unicode

str(obj).decode('utf8')
Run Code Online (Sandbox Code Playgroud)

对于已经 是值的对象,这仍然会失败unicode,因此您可能需要使用try..except来捕获这种情况:

try:
    obj = str(obj).decode('utf8')
except UnicodeEncodeError:
    # already unicode
    pass
Run Code Online (Sandbox Code Playgroud)

如果您尝试对字节字符串进行编码,Python 2 首先会隐式地为unicode您解码,这就是您获得UnicodeDecodeError.