[Tutor] 2-D array to string

Eli Brosh ebrosh at nana10.co.il
Fri Nov 23 16:43:21 CET 2007


Thank you very much Evert.
Starting from your advice, I used:
a=numpy.array([[100,2,3],[4,5,6],[7,8,9]])
s=repr(a).replace('array',' ')
s='      '+''.join([ c for c in s if c not in ('(', ')','[',']',',')])
print s

This gave the correct result.
So, the problem is solved.

The reason I wanted the array to be converted to string format is that I use such strings as an input to another program. 
The easiest thing so far, was to copy them from the MATLAB console.
Now, I have the same functionality in python, without '[' that appear if I just use:
print a

Thanks
Eli

-----הודעה מקורית-----
מאת: Evert Rol [mailto:evert.rol at gmail.com]
נשלח: ו 11/23/2007 16:24
אל: Eli Brosh
עותק לידיעה: tutor at python.org
נושא: Re: [Tutor] 2-D array to string
 
> I am starting to use pylab/numpy/scipy instead of MATLAB.
> I now have a real beginners question (I think it is not really  
> related to numpy)
> I have a two-dimensional array
> a=[[1,2,3],[4, 5, 6],[7,8,9]]
>
> Is there a simple way to turn it into a multiline string ?
>
> That is, turn a into:
> s='''1 2 3 \n 4 5 6 \n 7 8 9'''
>

Not a really easy way that I know of, but several solutions I can  
think of:
- turning the Python double list into a numpy array gives a multiline  
string, although differently formatted:
 >>> repr(numpy.array(a))
'array([[1, 2, 3],\n       [4, 5, 6],\n       [7, 8, 9]])'

- Using a double list comprehension can work:
 >>> '\n'.join([' '.join(str(aaa) for aaa in aa) for aa in a])
'1 2 3\n4 5 6\n7 8 9'

- You could use a regular expression to alter the numpy  
representation or the default Python representation into what you want.

- you could subclass the (numpy) array object and alter the __str__  
or __repr__ functions for convenience, although this may be bit overdone

There's probably a few more, perhaps even more elegant, that other  
people on the list may come up with.

But is there a specific reason you'd want it in this format, and not  
the default Python or numpy format? Perhaps you're writing data to a  
file?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071123/04e82889/attachment.htm 


More information about the Tutor mailing list