I am having problem creating a function that takes a string containing length values (eg: '32.0 mm / 1.259"`) and returning just the value in mm.
My current function parse is only able to handle strings that have just the mm value, but not if both mm and inches value exist.
Any help is greatly appreciated!
Regex pattern: re.sub("[^0-9.\-]", "", str)
import re
def parse(str):
if not str:
return None
str = str.lower()
return float(re.sub("[^0-9.\-]", "", str))
tests = ['12.3 mm', '12.3mm', '32.0 mm / 1.259"', '32.0mm / 1.259"']
for s in tests:
print( parse(s) )
Expected Output
12.3
12.3
32.0
32.0
Actual Output
12.3
12.3
ValueError: could not convert string to float: '32.01.259'
mm, 2) extracting numbers beforemm. My solution is very similar to Daniel's, but it does not extract the number in case of5. mmorph. since I am using a word boundary and my solution will also work in case of integer numbers beforemm.