I'm trying to pull data from a file that can either be an int or a float. I've found this regex that will pull these two types from the file (\d+(\.\d+)?)
, but the problem I'm having with it is that it's splitting the floats into two.
>>> import re
>>> line = "(gr_line (start 218.948 126.111) (end 218.948 143.637) (angle 90) (layer Edge.Cuts) (width 0.1) (tstamp 53D2B530))"
>>>
>>> print re.findall(r'\(start (\d+(\.\d+)?) (\d+(\.\d+)?)\)', line)
[('218.948', '.948', '126.111', '.111')]
>>>
The purpose of this is to get the starting coordinates which are defined by (start n n), but as you can see, it's taking 218.948 and splitting it into 218.948
and .948
. Same issue with 126.111
.
If the input string has an int in the starting brackets, I get the following:
>>> line = "(gr_line (start 218.948 126) (end 218.948 143.637) (angle 90) (layer Edge.Cuts) (width 0.1) (tstamp 53D2B530))"
>>> print re.findall(r'\(start (\d+(\.\d+)?) (\d+(\.\d+)?)\)', line)
[('218.948', '.948', '126', '')]
>>>
The issue here is the added empty index - not a huge problem, but a little inconvenient.
How can I format my regex so it captures either a float and return that float, or an int and return that int.
Hardware implementation of integer arithmetic is much faster (and simpler) than floating point arithmetic. Programming practices. Having data types enforces better programming practices, as the programmer must be aware of kind of data each variable stores.
Use the isinstance() function to check if a number is an int or float, e.g. if isinstance(my_num, int): . The isinstance function will return True if the passed in object is an instance of the provided class ( int or float ).
A "float" is a floating-point number - that is, a number and part of a number. If you need to store/represent a value that can be between integers, you could use a float. Floats use more RAM than integers, and there is a limit to the precision they can represent. Don't use a float unless you have a need.
In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.
You're capturing and saving two groupings with (\d+(\.\d+)?)
Try this:
(\d+(?:\.\d+)?)
That will only save the grouping from the entire float.
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