Regular expressions are not the best choice to see if a number is a float or not. It's complicated, given all the possible forms a valid floating point number can take and may take in the future versions of Python.
So it's much better to try to convert it and see if Python can do it, trap the exception if it can't.
I would do this like below:
def check_line(line_coord):
try:
return len([float(x) for x in line_coord.split()])==3
except ValueError:
return False
- create a list comprehension with float conversion on the line split according to spaces
- check if length of the list is equal to 3: return
True if OK
- protect that by a
ValueError exception, return False if exception caught
testing:
print(check_line("10 4.5dd 5.6")) # bogus float in 2nd position
print(check_line("10 5.6")) # only 2 fields
print(check_line("10 -40 5.6")) # 3 fields, all floats
False
False
True
EDIT: this above only checks if the values are here. Dawg suggested a way to return the triplet or None if error, like this:
def check_line(line_coord):
try:
x,y,z = map(float,line_coord.split())
return x,y,z
except ValueError:
return None
(map is faster because it won't create a temporary list). with the same test as before we get:
None
None
(10.0, -40.0, 5.6)