Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language


 
 
Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

Python Programming Language

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


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

En Mon, 04 Jun 2007 20:03:39 -0300, mike <needpass@gmail.com> escribi:

> 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

--
Gabriel Genellina

Great! It works.

Thanks a lot.

> 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
On 2007-06-05, Troels Thomsen <nej> wrote:

> 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!

Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc