gpt4 book ai didi

python - 从python中的unicode字符串获取字节

转载 作者:太空狗 更新时间:2023-10-29 20:35:35 25 4
gpt4 key购买 nike

我有一个 16 位大端 unicode 字符串,表示为 u'\u4132'

如何在 python 中将其拆分为整数 41 和 32?

最佳答案

这里有您可能需要的多种不同方式。

python 2:

>>> chars = u'\u4132'.encode('utf-16be')
>>> chars
'A2'
>>> ord(chars[0])
65
>>> '%x' % ord(chars[0])
'41'
>>> hex(ord(chars[0]))
'0x41'
>>> ['%x' % ord(c) for c in chars]
['41', '32']
>>> [hex(ord(c)) for c in chars]
['0x41', '0x32']

python 3:

>>> chars = '\u4132'.encode('utf-16be')
>>> chars
b'A2'
>>> chars = bytes('\u4132', 'utf-16be')
>>> chars # Just the same.
b'A2'
>>> chars[0]
65
>>> '%x' % chars[0]
'41'
>>> hex(chars[0])
'0x41'
>>> ['%x' % c for c in chars]
['41', '32']
>>> [hex(c) for c in chars]
['0x41', '0x32']

关于python - 从python中的unicode字符串获取字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4239666/

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