Python: Extract multiple float numbers from string
<p>Forgive me, I'm new to Python.</p>

<p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p>

<p>Example: </p>

<pre><code>"38.00,SALE ,15.20"
"69.99"
</code></pre>

<p>I'd like to return:</p>

<pre><code>[38.00, 15.20]
[69.99]
</code></pre>

<pre><code>def extract_nums(text):
    for item in text.split(','):
        try:
            yield float(item)
        except ValueError:
            pass

print list(extract_nums("38.00,SALE ,15.20"))
print list(extract_nums("69.99"))
</code></pre>

<hr>

<pre><code>[38.0, 15.2]
[69.99]
</code></pre>

<p>However by using <code>float</code> conversion you are <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow">losing precision</a>, If you want to keep the precision you can use <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code></a>:</p>

<pre><code>import decimal

def extract_nums(text):
    for item in text.split(','):
        try:
            yield decimal.Decimal(item)
        except decimal.InvalidOperation:
            pass

print list(extract_nums("38.00,SALE ,15.20"))
print list(extract_nums("69.99"))
</code></pre>

<hr>

<pre><code>[Decimal('38.00'), Decimal('15.20')]
[Decimal('69.99')]
</code></pre>

python string