isNumber? check

gyro gyromagnetic at excite.com
Tue Sep 30 08:10:52 EDT 2003


Rob Hunter wrote:
> 
> On Monday, September 29, 2003, at 10:20 AM, Gerrit Holl wrote:
> 
>> Rob Hunter wrote:
>>
>>> How do I check if a value is a number in Python?
>>>
>>> One way is (x == type(1)) and (x == type(1.2)) and (x ==
>>> type(2387482734274)) and ...
>>>
>>> but this seems kludgy.  Any better way?
>>
>>
>> Why do you want to do so?
> 
> 
> 
> I am writing an interpreter, and my parser has to decide if an 
> expression is a number or not.
> 
> 
> 
>> Maybe, it is better in your
>> case to just run the piece of code using the number, and
>> if it fails, it fails.
>> However, if you must, you need to
>> do type(x) is type(1) and ... etc., or isinstance(x, int)
>> and isinstance(x, float), etc.
>>
>> Gerrit.
> 
> 
> 

Below is a function I sometimes use.

-g


def is_a_number(x):
     """This function determines if its argument, x, is in the
     format of a number. It can be number can be in integer, floating
     point, scientific, or engineering format. The function returns True 
if the
     argument is formattted like a number, and False otherwise."""

     import re
     num_re = 
re.compile(r'^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?$')
     mo = num_re.match(x)
     if mo:
         return True
     else:
         return False






More information about the Python-list mailing list