Convert a text list to numbers?
<p>I am trying to use <code>float()</code> to convert the following list to numbers. But it always says <code>ValueError: could not convert string to float</code>.</p>

<p>I understand that this error occurs when there is something in text that cannot be treated as a number. But my list seems okay.</p>

<pre><code>a = ['4', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3']

b = [float(x) for x in a]
</code></pre>

<p>The problem is exactly what the Traceback log says: Could not convert string to float</p>

<ol>
<li>If you have a string with only numbers, python's smart enough to do what you're trying and converts the string to a float.</li>
<li>If you have a string with non-numerical characters, the conversion will fail and give you the error that you were having.</li>
</ol>

<p>You can strip whitespaces and then check for digits in the string.</p>

<pre><code> f = open('mytext.txt','r') 
 a = f.read().split()
 a = [each.strip() for each in a]
 a = [each for each in a if each.isdigit() ]
 b = [float(each) for each in a]  # or b = map(float, a)
 print b
 # just to make it clear written as separate steps, you can combine the steps
</code></pre>

python list text