> 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? _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
