通过强制转换为可逆的转换Python unicode?

Chr*_*lis 0 python string unicode

u在Python中将unicode字符串转换为(byte)字符串的正确方法是调用u.encode(someencoding).

不幸的是,我之前并不知道我曾经用过str(u)转换.特别是,我打电话str(u)强制u成为一个字符串,这样我就可以使它成为一个有效的搁置键(必须是str).

由于我没有遇到任何问题UnicodeEncodeError,我想知道这个过程是否可逆/无损.也就是说,我可以u = str(converted_unicode)(或u = bytes(converted_unicode)在Python 3中)获取原始内容u吗?

Mar*_*ers 5

在Python 2中,如果转换str()成功,那么您可以反转结果.使用str()上一个unicode值是使用的等效unicode_value.encode('ascii')和反向是简单地使用str_value.decode('ascii').使用unicode(str_value)将使用相同的隐式ASCII编解码器进行解码.

在Python 3中,调用str()unicode值只会为您提供相同的对象,因为在Python 3中str() Unicode类型.bytes()在没有编码的情况下使用Unicode值失败,您总是必须在Python 3中使用显式编解码器来在str和之间进行转换bytes.