0

I plan to insert string (colon) in between HEX in Python, i.e;

before: AABBCCDDEEFF112233 after: AA:BB:CC:DD:EE:FF:11:22:33

Can anybody here shed some light on how to achieve it.

Regards,

Al Rizal
  • 41
  • 1
  • 3
  • 2
    Have you tried solving your problem yourself before asking others to do it for you? – Blender Jun 17 '13 at 00:09
  • 1
    Use the grouper itertools recipe: http://docs.python.org/2/library/itertools.html#recipes and then join on `":"`. Done. – Patashu Jun 17 '13 at 00:10
  • 1
    Break it up into 2 character strings and then `':'.join(pieces)`. – martineau Jun 17 '13 at 00:11
  • `s = "AABBCCDDEEFF112233"\n"".join([(c if idx % 2 == 0 else c + ":") for c, idx in zip(s, range(0, len(s)))]).rstrip(":")` – Charles Salvia Jun 17 '13 at 00:18
  • if the original input is a bytestring (e.g., from integer), then `binascii.hexlify(bytesring, ':')` could be used, to insert colon into the hex representation. – jfs Feb 08 '23 at 16:57

1 Answers1

4

The answer to your question is here: Pythonic way to insert every 2 elements in a string

You could also use a step i.e. str[::x] to loop over every 2 characters to achieve this result.

myStr = 'AABBCCDDEEFF112233'
print ':'.join(myStr[i:i+2] for i in range(0, len(myStr), 2))
Community
  • 1
  • 1
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132