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]
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]
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')]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With