gpt4 book ai didi

python - 字符串编码 IDNA -> UTF-8 (Python)

转载 作者:行者123 更新时间:2023-12-02 00:49:33 26 4
gpt4 key购买 nike

字符串编码和格式总是让我感到困惑。

这是我所拥有的:

'ไทย'

我认为是 UTF-8,并且

'xn--o3cw4h'

这在 IDNA 编码中应该是一样的。但是,我无法弄清楚如何让 python 从一个转换为另一个。

我只是在尝试

a = u'xn--o3cw4h'
b = a.encode('idna')
b.decode('utf-8')

但我得到了完全相同的字符串('xn--o3cw4h',虽然不再是 unicode)。我目前使用的是 python 3.5。

最佳答案

要从一种编码转换为另一种编码,必须先将字符串解码为 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 结果:

'xn--o3cw4h'
'\xe0\xb9\x84\xe0\xb8\x97\xe0\xb8\xa2'
u'\u0e44\u0e17\u0e22'

可以看到,第一行是ไทย的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))

关于python - 字符串编码 IDNA -> UTF-8 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41067320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com