isNumber? check

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rob Hunter

    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(2387482734 274)) and ...

    but this seems kludgy. Any better way?

    Thanks,
    Rob


  • Peter Otten

    #2
    Re: isNumber? check

    Rob Hunter wrote:
    [color=blue]
    > How do I check if a value is a number in Python?[/color]
    [color=blue][color=green][color=darkred]
    >>> isinstance(1+1j , (float,int,long ,complex))[/color][/color][/color]
    True

    Peter

    Comment

    • Duncan Booth

      #3
      Re: isNumber? check

      Rob Hunter <rob@cs.brown.e du> wrote in
      news:mailman.10 64844761.11275. python-list@python.org :
      [color=blue]
      > 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(2387482734 274)) and ...
      >
      > but this seems kludgy. Any better way?
      >
      > Thanks,
      > Rob
      >
      >[/color]

      If you really have to test it then use:

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

      but mostly you shouldn't care.

      --
      Duncan Booth duncan@rcp.co.u k
      int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
      "\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?

      Comment

      • Terry Reedy

        #4
        Re: isNumber? check


        "Rob Hunter" <rob@cs.brown.e du> wrote in message
        news:mailman.10 64844761.11275. python-list@python.org ...[color=blue]
        > 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(2387482734 274)) and ...
        >
        > but this seems kludgy. Any better way?[/color]

        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


        Comment

        • Miki Tebeka

          #5
          Re: isNumber? check

          Hello Rob,[color=blue]
          > 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(2387482734 274)) and ...
          >
          > but this seems kludgy. Any better way?[/color]
          Same thing, different way:
          from types import IntType, LongType, FloatType
          def is_num(n):
          return n in (IntType, LongType, FloatType)

          HTH.
          Miki

          Comment

          Working...