convert string(<0.005) to floating point number(0.005) - python 2.7
Question
I have a sample of a list that i am iterating through, and trying to find the maximum value and require only the numbers. Im ignoring the blank spaces but need to change the '<0.005' to just 0.005, so i can use it.
lst = [['<0.005'],
['<0.005'],
['2.1'],
['2.1'],
['1.7'],
['0.098'],
[''],
['1.7'],
['0.91'],
['1.2']]
here is the relevant part of my code
for i in range(0,9):
if lst[i][0] != '':
if lst[i][0] == '<0.005'
lst[i][0] = 0.005
elif float(lst[i][0]) > maxP[i][0]:
maxP[i][0] = lst[i][0]
but the if lst[i][0] == '<0.005'
doesn't seem to work ie the code seems to just ignore it and i get the ValueError: could not convert string to float:
error for the second last line because it is still trying to access the <0.005 bits.
is there a way to fix this easily? ideally i would like it to deal with strings such as <0.098 and turn that into a float of 0.098
Any help / advice is greatly appreciated, thx
Solution
Your problem is an empty string (string with just white chars), not "<0.005" (which you handle correctly), you cannot convert empty string to float.
All you need is to add a .strip()
in second line
for i in range(0,9):
if lst[i][0].strip() != '':
if lst[i][0] == '<0.005':
lst[i][0] = 0.005
elif float(lst[i][0]) > maxP[i][0]:
maxP[i][0] = lst[i][0]
OTHER TIPS
You can use this regex to strip any characters that do not belong into a number:
value = re.sub(r'[^0-9.-]', '', value)
Of course it would still let something like ...5
or 5-5
through but if you just want to get rid of leading/trailing crap the regex does its job.
lst = [[float(re.sub(r'[^0-9.-]', '', x[0]))] for x in lst if x[0].strip()]
You could remove all characters that are not a number using a regex.
import re
def get_num_from_str(in_str):
return re.sub("[^0-9]", "", in_str)
Now you can let all items in the list be converted to a number
You can use regular expression
import re
lst = [['<0.005'],
['<0.005'],
['2.1 '],
['2.1 '],
['1.7 '],
['0.098 '],
[' '],
['1.7 '],
['0.91 '],
['1.2 ']]
def findMax(ilist):
result = 0.0
floatPattern = re.compile('\d+.\d+')
for el in ilist:
myFloat = floatPattern.search(el[0])
if myFloat != None:
if result < float(myFloat.group()):
result = float(myFloat.group())
return result
print findMax(lst)