[Edu-sig] How to verify an integer or float string

Kirby Urner urnerk@qwest.net
Thu, 04 Oct 2001 11:40:36 -0700


At 11:02 AM 10/4/2001 -0700, Titu Kim wrote:
>Hi,
>    I am trying to verify a string is a legal integer
>or float. Which method help me to do the job? Thanks a
>lot
>
>Kim Titu

If you just want a true/false answer as to whether
a string is a float or int, the code below will work.
It only tries to convert to float, because all legal
int strings, including longs, will also convert to
floats.

   >>> def isintorfloat(thestring):
          try:
              thevalue = float(thestring)
              return 1
           except:
             return 0

If you want to screen out long integers, then you need
a slightly more complicated method, employing similar
ideas.

Another approach, if you're not exposing your code to
potentially malicious users over the web, is to use
eval():

   >>> type(eval('12'))
   <type 'int'>
   >>> type(eval('12909023423423'))
   <type 'long'>
   >>> type(eval('1.0'))
   <type 'float'>

So a function might be:

   >>> def isintorfloat(thestring):
           try:
               thevalue = eval(thestring)
               if type(thevalue) == type(1):
                   return (1,int(thestring))
               elif type(thevalue) == type(1L):
                   return (1,long(thestring))
              elif type(thevalue) == type(1.0):
                   return (1,float(thestring))
               else:
                   return (0,0)
           except:
               return (0,0)

This version not only catches the strings that aren't legal,
it converts them, returning a tuple with 1 or 0 as a first
element (true or false) and the converted string as the 2nd
(but if the first is 0, then the 2nd defaults to 0 and may
be ignored).

    >>> isintorfloat('898989289823')
    (1, 898989289823L)
    >>> isintorfloat('8989892')
    (1, 8989892)
    >>> isintorfloat('8989892.0')
    (1, 8989892.0)
    >>> isintorfloat('8989892AAA')
    (0, 0)
    >>> isintorfloat('[1,2,3]')
    (0, 0)

There are ways to make eval safer than shown.

Kirby