Grak
Grak

Reputation: 99

How to check if a string has a specific format in Python

So my code should process lines and see if a line is a coordinate

"x y z"

example coordinate:

1.500 -6.002 0.007

with numbers representing the symbols and if so, I will process said line but if not, I'll leave it untouched. I gathered that re would be the right tool but I'm too new to know-how based on the different scenarios that have already happened in the past.

Upvotes: 1

Views: 737

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140316

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)

Upvotes: 2

Related Questions