By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,922 Members | 1,493 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,922 IT Pros & Developers. It's quick & easy.

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

P: n/a
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

Jun 4 '07 #1
Share this Question
Share on Google+
4 Replies


P: n/a
En Mon, 04 Jun 2007 20:03:39 -0300, mike <ne*********@gmail.comescribió:
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
pya='01234'
pyfor c in a:
.... print "%#x" % ord(c),
....
0x30 0x31 0x32 0x33 0x34
py>

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

--
Gabriel Genellina

Jun 4 '07 #2

P: n/a
Great! It works.

Thanks a lot.

Jun 5 '07 #3

P: n/a

Great! It works.
There is a builtin function called hex() that does the same, but also shares
the same problem as the solution above:
>>hex(10)
'0xa'
>>>
This is probably not "nice" in your printouts, it doesn't allign.
with the printf inspired solution you can set the precision like this:
>>a = "12\n34"
for c in a:
.... print "%#04x" % ord(c),
....
0x31 0x32 0x0a 0x33 0x34
>>>

regards troels
Jun 5 '07 #4

P: n/a
On 2007-06-05, Troels Thomsen <nejwrote:
with the printf inspired solution you can set the precision like this:
>>>a = "12\n34"
for c in a:
... print "%#04x" % ord(c),
...
0x31 0x32 0x0a 0x33 0x34
And if you just want to do the conversion w/o printing:
>>a = "12\n34"
>>' '.join(('%#04x' % ord(c) for c in a))
'0x31 0x32 0x0a 0x33 0x34'
>>' '.join(('%02x' % ord(c) for c in a))
'31 32 0a 33 34'

--
Grant Edwards grante Yow! Vote for ME -- I'm
at well-tapered, half-cocked,
visi.com ill-conceived and
TAX-DEFERRED!
Jun 5 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.