Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Extract multiple float numbers from string

Tags:

python

string

Forgive me, I'm new to Python.

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.

Example:

"38.00,SALE ,15.20"
"69.99"

I'd like to return:

[38.00, 15.20]
[69.99]
like image 793
GeneralBear Avatar asked Oct 15 '16 03:10

GeneralBear


3 Answers

You could also use regex to do this

import re
s = "38.00,SALE ,15.20"
p = re.compile(r'\d+\.\d+')  # Compile a pattern to capture float values
floats = [float(i) for i in p.findall(s)]  # Convert strings to float
print floats

Output:

[38.0, 15.2]
like image 125
sisanared Avatar answered Oct 05 '22 16:10

sisanared


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"))

[38.0, 15.2]
[69.99]

However by using float conversion you are losing precision, If you want to keep the precision you can use decimal:

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"))

[Decimal('38.00'), Decimal('15.20')]
[Decimal('69.99')]
like image 22
jamylak Avatar answered Oct 05 '22 14:10

jamylak


You said you're only interested in floats at the start and end of the string, so assuming it's comma-delimited:

items = the_string.split(',')
try:
    first = float(items[0])
except (ValueError, IndexError):
    pass
try:
    second = float(items[-1])
except (ValueError, IndexError):
    pass

We have to wrap the operations in exception handlers since the value might not be a valid float (ValueError) or the index might not exist in the list (an IndexError).

This will handle all cases including if one or both of the floats is omitted.

like image 40
machine yearning Avatar answered Oct 05 '22 14:10

machine yearning