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

Seth David Schoen schoen@loyalty.org
Thu, 4 Oct 2001 11:26:01 -0700


Titu Kim writes:

> 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

Perhaps checking for exceptions in the conversion process:

def can_be_float(s):
	try:
		float(s)
	except ValueError:
		return 0
	return 1

The float function might raise other exceptions, too; those are the
ones which came to mind quickly.  (It doesn't appear to raise an
OverflowError, though.)

It seems to me that, if a string can be a legal integer, it can also
be a legal float.

-- 
Seth David Schoen <schoen@loyalty.org> | Its really terrible when FBI arrested
Temp.  http://www.loyalty.org/~schoen/ | hacker, who visited USA with peacefull
down:  http://www.loyalty.org/   (CAF) | mission -- to share his knowledge with
     http://www.freesklyarov.org/      | american nation.  (Ilya V. Vasilyev)