Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether string might be type-cast to float in Python? [duplicate]

Is there some function like str.isnumeric but applicable to float?

'13.37'.isnumeric() #False  

I still use this:

def isFloat(string):
    try:
        float(string)
        return True
    except ValueError:
        return False
like image 380
Andrew Avatar asked Mar 01 '10 15:03

Andrew


People also ask

How do you check if an input is a float Python?

To check if the input string is an integer number, convert the user input to the integer type using the int() constructor. To check if the input is a float number, convert the user input to the float type using the float() constructor.

How do you check if a string can be converted to an int Python?

To check if a string is integer in Python, use the isdigit() method. The string isdigit() is a built-in Python method that checks whether the given string consists of only digits. In addition, it checks if the characters present in the string are digits or not.


3 Answers

As Imran says, your code is absolutely fine as shown.

However, it does encourage clients of isFloat down the "Look Before You Leap" path instead of the more Pythonic "Easier to Ask Forgiveness than Permission" path.

It's more Pythonic for clients to assume they have a string representing a float but be ready to handle the exception that will be thrown if it isn't.

This approach also has the nice side-effect of converting the string to a float once instead of twice.

like image 118
Jon-Eric Avatar answered Oct 17 '22 12:10

Jon-Eric


A more complete generalization:

    def strType(xstr):
        try:
            int(xstr)
            return 'int'
        except:
            try:
                float(xstr)
                return 'float'
            except:
                try:
                    complex(xstr)
                    return 'complex'
                except:
                    return 'str'


    print("4", strType("4"))
    print("12345678901234567890", strType("12345678901234567890"))
    print("4.1", strType("4.1"))
    print("4.1+3j", strType("4.1+3j"))
    print("a", strType("a"))
like image 4
Leandro Lima Avatar answered Oct 17 '22 10:10

Leandro Lima


Your code is absolutely fine. Regex based solutions are more likely to be error prone.

Quick testing with timeit reveals float(str_val) is indeed faster than re.match()

>>> timeit.timeit('float("-1.1")')
1.2833082290601467
>>> timeit.timeit(r"pat.match('-1.1')", "import re; pat=re.compile(r'^-?\d*\.?\d+(?:[Ee]-?\d+)?$');")
1.5084138986904527

And the regex used above fails one edge case, it can't match '-1.', although float() will happily convert it to proper float value.

like image 2
Imran Avatar answered Oct 17 '22 12:10

Imran