469,266 Members | 1,679 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,266 developers. It's quick & easy.

isNumber? check

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?

Thanks,
Rob
Jul 18 '05 #1
4 43706
Rob Hunter wrote:
How do I check if a value is a number in Python?

isinstance(1+1j, (float,int,long,complex))

True

Peter

Jul 18 '05 #2
Rob Hunter <ro*@cs.brown.edu> wrote in
news:ma**********************************@python.o rg:
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?

Thanks,
Rob


If you really have to test it then use:

isinstance(x, (int, long, float, complex))

but mostly you shouldn't care.

--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #3

"Rob Hunter" <ro*@cs.brown.edu> wrote in message
news:ma**********************************@python.o rg...
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?


type(x) in (int, long, float, complex) # or,
isinstance(x, (int, long, float, complex)) # now preferred, I think

But how about x=x-0?
This also accepts a user-defined number-class instance.

This option gets to the point that 'number' is not exactly defined in
either Python or mathematics. So checking for 'numberness' may or may
not be what you need .

Terry J. Reedy
Jul 18 '05 #4
Hello Rob,
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?

Same thing, different way:
from types import IntType, LongType, FloatType
def is_num(n):
return n in (IntType, LongType, FloatType)

HTH.
Miki
Jul 18 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by laredotornado | last post: by
13 posts views Thread by Rainer Deyke | last post: by
33 posts views Thread by Steven Bethard | last post: by
7 posts views Thread by Mike L | last post: by
2 posts views Thread by Jefe | last post: by
35 posts views Thread by pinkfloydhomer | last post: by
2 posts views Thread by sloan | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.