在遗留中发现:
somevar.encode('utf-8').decode('utf-8')
当我们不试图捕获编码错误时,我们能发现这种构造有用吗?
最佳答案
Python 2.7.6 解释器中的实验:
a = u"string"
a
输出:u'字符串'
b = a.encode('utf-8').decode('utf-8')
b
输出:u'字符串'
b = a.decode('utf-8').encode('utf-8')
b
输出:'字符串'
a = "string"
a
输出:'字符串'
b = a.encode('utf-8').decode('utf-8')
b
输出:u'字符串'
b = a.decode('utf-8').encode('utf-8')
b
输出:'字符串'
注意,无论原始字符串是否为 Unicode,encode -> Decode 的输出都将是 Unicode 字符串。解码 ->编码的输出将不是unicode字符串。不过,需要注意的是,由于字符串是不可变的,因此您发布的代码行除了检查 UnicodeError 之外没有任何用处,因为它无法捕获函数调用的返回值。
编码 -> 解码构造的唯一实际效果是通过它(并从返回中捕获)的所有字符串都将是 Unicode 字符串。为什么你想要这样做而不是 unicode_string = unicode(normal_string,encoding='UTF-8')
我不知道。
关于Python:编码后立即解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24759250/