[英]Which is the right way to convert Unicode string to Hexadecimal in Python 3? [on hold]
我在 Python 中找到了两种将字符串转换为十六进制的方法:
第一种方式:
ss = "Ế string"
sss = [hex(ord(sc)) for sc in ss]
ssss = ''.join(sss).replace('0x', '')
print(ssss) # The result is 1ebe20737472696e67
第二种方式:
import codecs
ss = "Ế string"
sss = codecs.encode(codecs.encode(ss, 'utf-8'), 'hex')
print(sss.decode('utf-8')) # The result is: e1babe20737472696e67
两种方式返回不同的结果,哪个是正确的代码?
我不知道您为什么要将字符串转换为这样的十六进制,但我认为第二种方法更好:
ss = "Ế string"
# first decode the string to get the correct code point for utf8.
ss = ss.encode('utf-8')
# then convert the int code point to hex
sss = [hex(sc) for sc in ss]
print(''.join(sss).replace('0x', ''))
现在为什么因为使用decode
会将字符串转换为byte
序列,它们是 integer 的序列,每个值都是指定编解码器('utf8')
中character
的code point
。 此code point
从一个codec
更改为另一个。 基本上,它使用另一个codec
将字符串转换为utf8
中的hex
表示将生成不同的hex
表示。
我找到了答案,第一种方式返回一个UTF-16BE编码的字符串,第二种方式返回一个UTF-8编码的字符串。 如果我将第二种方式更改为codecs.encode(codecs.encode("ẵ", "utf-16be"),"hex")
那么它们将返回相同的结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.