The Python Oracle

Print a string as hexadecimal bytes

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Luau

--

Chapters
00:00 Print A String As Hexadecimal Bytes
00:13 Accepted Answer Score 259
00:26 Answer 2 Score 162
00:32 Answer 3 Score 60
00:49 Answer 4 Score 26
01:11 Answer 5 Score 24
02:00 Thank you

--

Full question
https://stackoverflow.com/questions/1221...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #hex #ordinalindicator

#avk47



ACCEPTED ANSWER

Score 260


You can transform your string to an integer generator. Apply hexadecimal formatting for each element and intercalate with a separator:

>>> s = "Hello, World!"
>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:2c:20:57:6f:72:6c:64:21



ANSWER 2

Score 163


':'.join(x.encode('hex') for x in 'Hello, World!')



ANSWER 3

Score 60


For Python 2.x:

':'.join(x.encode('hex') for x in 'Hello, World!')

The code above will not work with Python 3.x. For 3.x, the code below will work:

':'.join(hex(ord(x))[2:] for x in 'Hello, World!')



ANSWER 4

Score 24


Some complements to Fedor Gogolev's answer:

First, if the string contains characters whose ASCII code is below 10, they will not be displayed as required. In that case, the correct format should be {:02x}:

>>> s = "Hello Unicode \u0005!!"
>>> ":".join("{0:x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:5:21:21'
                                           ^

>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:75:6e:69:63:6f:64:65:20:05:21:21'
                                           ^^

Second, if your "string" is in reality a "byte string" -- and since the difference matters in Python 3 -- you might prefer the following:

>>> s = b"Hello bytes \x05!!"
>>> ":".join("{:02x}".format(c) for c in s)
'48:65:6c:6c:6f:20:62:79:74:65:73:20:05:21:21'

Please note there is no need for conversion in the above code as a bytes object is defined as "an immutable sequence of integers in the range 0 <= x < 256".