Urgent: "\" in strings?

Alex Martelli alex at magenta.com
Tue Aug 8 06:58:47 EDT 2000


Haven't seen Nicks's original msg, but, given the urgency, I'm
"kidnapping" Ruud's reply (and CC'ing Nick by mail):

"Ruud de Rooij" <*@spam.ruud.org> wrote in message
news:87bsz4ysof.fsf at hobbes.home.ruud.org...
> Nick Bower <bowern at ses.curtin.edu.au> writes:
>
> > I'm messing with PIL, and the only way I can see to get a palette out of
> > an image returns a string such as:
> >
> > '\000\000\001\002' etc
> >
> > which is not that weird until you do a s[0] and it returns:
> >
> > '\000' instead of '\
> >
> > How do I convert this string to numbers?
>
> Those \000 indicate characters with a value outside the printable
> ASCII range.  So '\000' is a single character with the ASCII value
> 0.
>
> ord(s[0]) is probably what you are looking for to convert them to
> numbers.

If you want to convert each byte separately, yes, that works.  The
struct module might also be applicable:

>>> import struct
>>> data='\000\000\001\002'
>>> struct.unpack(len(data)*'B',data)
(0, 0, 1, 2)

and this also lets you convert 16-bit numbers or whatever.

Or, the array module:

>>> import array
>>> a=array.array('B',data)
>>> a.tolist()
[0, 0, 1, 2]


As usual (though it's not much stressed:-), Python provides a LOT
of ways to approach the issue... all pretty good!-)


Alex






More information about the Python-list mailing list