如何从ISO-8859-1格式转换为UTF-8,然后转换为十六进制格式字符串python

时间:2018-10-03 23:29:38

标签: python utf-8 hex

如何将UTF-8格式的字符“戗”转换为十六进制值并将其存储为字符串“ 0xe6 0x88 0xa7”。

with open(fromFilename,  encoding = "ISO-8859-1") as f:
    while True:
        c = f.read(1)
        if not c:
            print ("End of file")
            break
        print ("Read a character: %c", c)
        newC = repr(c.encode('utf-8'))
        print ("Read a decode character: %c", newC)
        newString = newString + newC

这是我的代码。请让我知道怎么了。

1 个答案:

答案 0 :(得分:1)

这在Python 3.7中对我有效

a = '戧'
encoded_bytes = a.encode(encoding='utf-8')
print(' '.join([hex(b) for b in encoded_bytes]))

>>> 0xe6 0x88 0xa7