check if object is number

marco pippo at tin.it
Fri Feb 11 18:22:01 EST 2005


Steven Bethard wrote:
> Is there a good way to determine if an object is a numeric type? 
.
.
.
> 
> Ideas?
Maybe this can help?

def isnumber(x):
     try:
         return(x == x-0)
     except:
         return False

print '1:\t', isnumber(1)
print '1.25:\t', isnumber(1.25)
print '1.0 / 7:\t', isnumber(1.0 / 7)
print '1+0j:\t', isnumber((1+0j))
print '"spam":\t', isnumber("spam")

output:

1:	True
1.25:	True
1.0/7:	True
1+0j:	True
"spam":	False

Ooops! While checking other posts I realized that this is almost the 
same as Dan Bishop's solution.

Marco



More information about the Python-list mailing list