[Numpy-discussion] Numeric odd tostring() behaviour

Chris Barker Chris.Barker at noaa.gov
Tue Oct 21 15:09:03 CDT 2003


Russell Valentine wrote:

>    It may be my fault, but I think the following behaviour is odd. If I
> try to change a array to a string it seems like it adds a lot of extra
> zero characters. Take the following script attached as a example, it gives
> me this output.

You've misunderstood what tostring() is supposed to do. It takes the
BINARY data representing the array, and dumps it into a Python string as
a string of bytes. It is NOT doing a chr() on each element. As an
example:

>>> a = array((1.0))
>>> # a is now a one element Python Float (C double, 8 bytes)
>>> s = a.tostring()
>>> len(s)
8
>>> print repr(s)
'\x00\x00\x00\x00\x00\x00\xf0?'
>>>

And there are your 8 bytes.

By the way, in your code:
tast = ""
for value in ta:
    tast += chr(value)

you could probably speed it up quite a bit by doing this instead:
tast = []
for value in ta:
    tast.append(value)
tast = "".join(tast)

Using += with a string creates a new string, one charactor longer, each
time. Appending to an a list is much faster, and the string join method
is pretty quick also.


-- 
Christopher Barker, Ph.D.
Oceanographer
                                    		
NOAA/OR&R/HAZMAT         (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov




More information about the Numpy-discussion mailing list