0

I'm kind of new to python, and this is probably going to sound like a dumb question, but it's hurting my brain trying to figure it out.

I have the following code

myarray = bytes([0x01, 0xAF, 0x45, 0xA9])

print('-'.join(format(x,'02X') for x in myarray))

output: 01-AF-45-A9

It does what I want it to, but as I found it on another question i'm not 100% on part of it.

How is the 'x' in the for loop passed backwards to the 'format(x,'02X')' function?

Logically I would have written it something like this. I wrap the call to format with the 'for' loop, in the above example the loop is written after the call to format.

hexstring = ''

for x in myarray:
    hexstring += format(x,'02X') + '-'

hexstring = hexstring[:-1]
print(hexstring)

Which results in exactly the same output.

This is probably some fundamental thing about how loops in python work, or it's something peculiar about the 'join' function.

Ryan.
  • 77
  • 1
  • 5

0 Answers0