[Tutor] Extract lines from a multinile string-Thanks

John Fouhy john at fouhy.net
Wed Oct 10 23:31:53 CEST 2007


Hi Eli,

Please use "reply to all" so that other list users can follow the
conversation if they wish.

On 11/10/2007, Eli Brosh <ebrosh at nana10.co.il> wrote:
> Thank you very much for the reply.
> No, I did not check that there is no control character in the multiline.
> I just assumed that it is not there if I did not put it there.
> Now, I understand it better.
>
> I am now trying to use python instead of MATLAB.
> I found it somewhat annoying that in order to define a two-dimensional array
> in python I need some may [[[]]] and ,,:
> A = array([[0,   1,  2,  3],   # initialize 2-d array
>            [4,   5,  6,  7],
>            [8,   9, 10, 11],
>            [12, 13, 14, 15]])
>
> I thought it could be good to have a function str2array into which you  put
> a string and it is turned into an array:
>
> A = str2array(''' 1  2  3
>            4  5 6  7
>             8 9 10 11
>            12 13 14 15''')
>
> Is there already such a function ?

I'm not aware of any such function.  But you could write it simply as:

def str2array(arrayStr):
    return [[int(i) for i in s.split()] for s in arrayStr.split('\n')]

(or replace int() by float() if you expect floating point numbers)

But if you want to use python to replace matlab, you should look in to
numpy.  numpy is a popular python module that supports scientific
computation.  It includes support for two-dimensional arrays.  If you
use numpy, you may get some support on this list, but there are also
numpy-specific lists.

-- 
John.


More information about the Tutor mailing list