Converting a string to a list of lists
<p>Using Python 2.7, I want to convert a string in the following format to a list of lists:</p>

<pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
&gt;&gt;&gt; ...
&gt;&gt;&gt; result = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
</code></pre>

<p>I did manage to do just that, but it seems sloppy.</p>

<pre><code>&gt;&gt;&gt; value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
&gt;&gt;&gt; val2 = value.replace('[[', '').replace(']]', '').split('] [')
&gt;&gt;&gt; val2
['1 0 0 0', '0 1 0 0', '0 0 1 0', '0 0 0 1']
&gt;&gt;&gt; val_final = [[float(x) for x in x] for x in [x.replace(' ', '') for x in val2]]
&gt;&gt;&gt; val_final
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
</code></pre>

<p><strong>Is there a better, cleaner way to do this that would be more robust?</strong></p>

<p>Note: I do expect to only have integer or float values in the string (context: it's a 4x4 matrix corresponding to an object position in a 3D environment).</p>

<hr>

<p><strong>Edit:</strong>
Alternative value could contain floats like so:</p>

<pre><code>&gt;&gt;&gt; value = "[[9.231 -0.123 -2 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"
&gt;&gt;&gt; ...
&gt;&gt;&gt; result = [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
</code></pre>

<p>Similar to the Johan Dahlin's answer:</p>

<p>Instead of using <em>json</em> parser, you can user the integrated Python <a href="https://docs.python.org/2/library/ast.html" rel="nofollow">Abstract Syntax Trees</a> parser:</p>

<p>Like this:</p>

<pre><code>value = "[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]"

import ast

matrix = ast.literal_eval(value.replace(" ", ", "))
print(matrix)
# -&gt; [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
</code></pre>

<p>With floats values:</p>

<pre><code># -&gt; [[9.231, -0.123, -2, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
</code></pre>

<p>To "force" conversion to <strong>float</strong>, just write:</p>

<pre><code>matrix = [[float(x) for x in row] for row in matrix]
print(matrix)
# -&gt; [[9.231, -0.123, -2.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
</code></pre>

python python-2.7