0

可能重复:
如何在 Python 中将列表拆分为大小均匀的块?
按字符数拆分字符串

我有一个字符串(十六进制),例如:

717765717777716571a7202020

我需要把它变成以下格式:

0x71,0x77,0x65,0x71,0x77,0x77...

我不确定最好的方法是什么

4

2 回答 2

5
>>> s = '717765717777716571a7202020'
>>> ['0x' + s[i:i+2] for i in range(0, len(s), 2)]
['0x71', '0x77', '0x65', '0x71', '0x77', '0x77', '0x71', '0x65', '0x71', '0xa7', '0x20', '0x20', '0x20']

如果您想要一个逗号分隔的字符串作为结果,您可以使用以下内容:

>>> ','.join('0x' + s[i:i+2] for i in range(0, len(s), 2))
'0x71,0x77,0x65,0x71,0x77,0x77,0x71,0x65,0x71,0xa7,0x20,0x20,0x20'
于 2012-11-02T20:28:47.367 回答
0

其他方式。

s = '717765717777716571a7202020'

print ','.join('0x'+''.join(d) for d in zip( *[iter(s)]*2 ))

输出:

0x71,0x77,0x65,0x71,0x77,0x77,0x71,0x65,0x71,0xa7,0x20,0x20,0x20
于 2012-11-02T21:07:57.197 回答