Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex for float or int while not splitting the float into two floats

Tags:

python

regex

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.

like image 647
Seth Koberg Avatar asked Aug 06 '14 21:08

Seth Koberg


People also ask

Why use integers over floats and not just floats all the time?

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.

How do you check for floats in Python?

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 ).

Can we use float instead of int?

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.

How do you get the float number in a string in python?

In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.


1 Answers

You're capturing and saving two groupings with (\d+(\.\d+)?)

Try this:

(\d+(?:\.\d+)?)

That will only save the grouping from the entire float.

like image 131
celeritas Avatar answered Oct 04 '22 03:10

celeritas