要从一种编码转换为另一种编码,必须首先将字符串解码为Unicode,然后在目标编码中再次编码。在
例如:idna_encoded_bytes = b'xn o3cw4h'
unicode_string = idna_encoded_bytes.decode('idna')
utf8_encoded_bytes = unicode_string.encode('utf-8')
print (repr(idna_encoded_bytes))
print (repr(utf8_encoded_bytes))
print (repr(unicode_string))
Python2结果:
^{pr2}$
如您所见,第一行是ไทย的IDNA编码,第二行是utf8编码,最后一行是Unicode代码点U-0E44、U-0E17和U-0E22的未编码序列。在
要一步完成转换,只需将操作链起来:utf8_encoded_bytes = idna_encoded_bytes.decode('idna').encode('utf8')
回复评论:I'm starting with isn't b'xn o3cw4h' but just the string 'xn o3cw4h'. [in Python3].
你那儿有只怪鸭子。显然,您已经对存储在unicode字符串中的数据进行了编码。我们需要以某种方式将其转换为bytes对象。一种简单的方法是使用(令人困惑的)ASCII编码:improperly_encoded_idna = 'xn o3cw4h'
idna_encoded_bytes = improperly_encoded_idna.encode('ascii')
unicode_string = idna_encoded_bytes.decode('idna')
utf8_encoded_bytes = unicode_string.encode('utf-8')
print (repr(idna_encoded_bytes))
print (repr(utf8_encoded_bytes))
print (repr(unicode_string))