Converting a string representation of an array to an actual array in python
Question: Hi doing some stuff over a network and wondering if there is any way of
converting python array as a string back into a python array.. for example

    
    
    x = "[1,2,3,4]"
    

converting x to

    
    
    x_array = [1,2,3,4]
    

Bonus if it can also work for numpy multidimensional arrays!


Answer: For the normal arrays, use
[`ast.literal_eval`](http://docs.python.org/2/library/ast.html#ast.literal_eval):

    
    
    >>> from ast import literal_eval
    >>> x = "[1,2,3,4]"
    >>> literal_eval(x)
    [1, 2, 3, 4]
    >>> type(literal_eval(x))
    <type 'list'>
    >>>
    

`numpy.array`'s though are a little tricky because of how Python renders them
as strings:

    
    
    >>> import numpy as np
    >>> x = [[1,2,3], [4,5,6]]
    >>> x = np.array(x)
    >>> x
    array([[1, 2, 3],
           [4, 5, 6]])
    >>> x = str(x)
    >>> x
    '[[1 2 3]\n [4 5 6]]'
    >>>
    

One hack you could use though for simple ones is replacing the whitespace with
commas using [`re.sub`](http://docs.python.org/2/library/re.html#re.sub):

    
    
    >>> import re
    >>> x = re.sub("\s+", ",", x)
    >>> x
    '[[1,2,3],[4,5,6]]'
    >>>
    

Then, you can use `ast.literal_eval` and turn it back into a `numpy.array`:

    
    
    >>> x = literal_eval(x)
    >>> np.array(x)
    array([[1, 2, 3],
           [4, 5, 6]])
    >>>
    

