I have a hex string I want to print out 32 characters at a time, starting from the right and going left. E.g.
11010401c3cf0e0e383434d0c0c302c2cb0a0a28242490808201c1c7060618141450404100c0c302020804041
should print as
<code>60618141450404100c0c302020804041
0c302c2cb0a0a28242490808201c1c70
000000011010401c3cf0e0e383434d0c
</code>
<code>60618141450404100c0c302020804041
0c302c2cb0a0a28242490808201c1c70
000000011010401c3cf0e0e383434d0c
</code>
60618141450404100c0c302020804041
0c302c2cb0a0a28242490808201c1c70
000000011010401c3cf0e0e383434d0c
I tried:
<code>for i in range(len(hex_str)//32+1):
print(hex_str[-32*(i+1):-32*i].zfill(32))
</code>
<code>for i in range(len(hex_str)//32+1):
print(hex_str[-32*(i+1):-32*i].zfill(32))
</code>
for i in range(len(hex_str)//32+1):
print(hex_str[-32*(i+1):-32*i].zfill(32))
but this gives the incorrect output:
<code>00000000000000000000000000000000
0c302c2cb0a0a28242490808201c1c70
000000011010401c3cf0e0e383434d0c
</code>
<code>00000000000000000000000000000000
0c302c2cb0a0a28242490808201c1c70
000000011010401c3cf0e0e383434d0c
</code>
00000000000000000000000000000000
0c302c2cb0a0a28242490808201c1c70
000000011010401c3cf0e0e383434d0c
This is because in the first iteration, -32*i
evaluates to 0 and so the slicing is hex_str[-32:0]
which returns None
. I know the proper syntax is hex_str[-32:]
, but how do I get that in a loop like this? My best solution is
<code>for i in range(len(inject)//32+1):
print(hex_str[-32*(i+1):-32*i or None].zfill(32))
</code>
<code>for i in range(len(inject)//32+1):
print(hex_str[-32*(i+1):-32*i or None].zfill(32))
</code>
for i in range(len(inject)//32+1):
print(hex_str[-32*(i+1):-32*i or None].zfill(32))
Feels ugly though. Should I just be OK with that feeling, or is there something slicker I’m unaware of?
1