I decided to create a small program that accepts hexadecimal code

646с726а77206а6с6с6548 

And converts to

 \x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64 

But I do not understand how to do this?

There have been attempts

 a = "646с726а77206а6с6с6548" b = a[::-1] hexcode = "" for i in b: hexcode+=b 

But I do not know how to do it so that the cycle throws 2 symbols at a time?

  • Reversing lines of two characters? for i in range(0, len(a), 2): hexcode = a[i:i+2] + hexcode but this is not “pitonic”;) - MBo
  • why two? I would like to hexcode = "\x" two characters in the variable hexcode = "\x" that would result in "\ x48 \ x65 \ x6c" - kombat

1 answer 1

Well, somehow it turns out:

 a = '646с726а77206а6с6с6548' hexcode = ''.join([r'\x' + a[i:i+2] for i in range(0, len(a), 2)]) print(hexcode) # \x64\x6с\x72\x6а\x77\x20\x6а\x6с\x6с\x65\x48 hexcode = ''.join(reversed([r'\x' + a[i:i+2] for i in range(0, len(a), 2)])) print(hexcode) # \x48\x65\x6с\x6с\x6а\x20\x77\x6а\x72\x6с\x64