Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a string is a number (float)?

What is the best possible way to check if a string can be represented as a number in Python?

The function I currently have right now is:

def is_number(s):     try:         float(s)         return True     except ValueError:         return False 

Which, not only is ugly and slow, but also seems clunky. However, I haven't found a better method because calling float() in the main function is even worse.

like image 259
Daniel Goldberg Avatar asked Dec 09 '08 20:12

Daniel Goldberg


People also ask

How do you check if a variable is a float?

The is_float() function checks whether a variable is of type float or not. This function returns true (1) if the variable is of type float, otherwise it returns false.

How do you determine if a string is a number in Python?

Use the isdigit() Method to Check if a Given Character Is a Number in Python. The isdigit() function is used to check whether all the characters in a particular string are digits. It returns a True value if all the characters are digits. Exponents are also confined in the scope of digits.


2 Answers

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

>>> a = "03523" >>> a.isdigit() True >>> b = "963spam" >>> b.isdigit() False 

String Methods - isdigit(): Python2, Python3

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal

like image 171
Zoomulator Avatar answered Sep 24 '22 12:09

Zoomulator


Which, not only is ugly and slow

I'd dispute both.

A regex or other string parsing method would be uglier and slower.

I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

The issue is that any numeric conversion function has two kinds of results

  • A number, if the number is valid
  • A status code (e.g., via errno) or exception to show that no valid number could be parsed.

C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

I think your code for doing this is perfect.

like image 27
S.Lott Avatar answered Sep 24 '22 12:09

S.Lott