how to print out each single char from a string in HEX format?

M

mike

guys,

I've researched python pretty much but still have no idea how to print
out each single character from a string in HEX format? Hope someone
can give me some hints. Thanks a lot.

e.g. ###here is a string

a='01234'

###how to print out it out in this way

0x31 0x31 0x32 0x33 0x34
 
G

Gabriel Genellina

I've researched python pretty much but still have no idea how to print
out each single character from a string in HEX format? Hope someone
can give me some hints. Thanks a lot.

e.g. ###here is a string

a='01234'

###how to print out it out in this way

0x31 0x31 0x32 0x33 0x34

py> a='01234'
py> for c in a:
.... print "%#x" % ord(c),
....
0x30 0x31 0x32 0x33 0x34
py>

See <http://docs.python.org/lib/built-in-funcs.html#l2h-55> for the ord()
function and <http://docs.python.org/lib/typesseq-strings.html> for the
"%#x" format
 
T

Troels Thomsen

Great! It works.

There is a builtin function called hex() that does the same, but also shares
the same problem as the solution above:

This is probably not "nice" in your printouts, it doesn't allign.


with the printf inspired solution you can set the precision like this:
.... print "%#04x" % ord(c),
....
0x31 0x32 0x0a 0x33 0x34

regards troels
 
G

Grant Edwards

with the printf inspired solution you can set the precision like this:

... print "%#04x" % ord(c),
...
0x31 0x32 0x0a 0x33 0x34

And if you just want to do the conversion w/o printing:

'0x31 0x32 0x0a 0x33 0x34'

'31 32 0a 33 34'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top