Python - 将字符串拆分为配对字符列表

时间:2012-11-02 20:24:33

标签: python string list hex

  

可能重复:
  How do you split a list into evenly sized chunks in Python?
  Split string by count of characters

我有一个字符串(十六进制),类似于:

717765717777716571a7202020

我需要把它变成格式:

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

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

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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