0

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Split string by count of characters

I have a string (which is hex), something like:

717765717777716571a7202020

I need to get it into the format:

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

I'm not sure what the best method would be though

Community
  • 1
  • 1
jossgray
  • 497
  • 6
  • 20
  • 3
    A string can be accessed just like a normal list, so all of the answers on that question will answer this one too. – Brendan Long Nov 02 '12 at 20:27

2 Answers2

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']

If you want a comma-separated string as the result, you can use the following:

>>> ','.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'
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

Another way.

s = '717765717777716571a7202020'

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

Output:

0x71,0x77,0x65,0x71,0x77,0x77,0x71,0x65,0x71,0xa7,0x20,0x20,0x20
martineau
  • 119,623
  • 25
  • 170
  • 301