Hi,
Is a string is valid "float"? Interesting question.
I propose here three functions
def IsFloat2(s):
try:
x = float(s)
return True
except:
return False
def IsFloat1(s):
try:
return isinstance(float(s), float)
except:
return False
def IsFloat(s):
try:
x = float(s)
if 'INF' in str(x):
return False
else:
return True
except:
return False
IsFloat2: this is the method proposed by Chris
IsFloat1: same method as IsFloat2 but this one
uses Python 2.3 capability -isinstance-
IsFloat: my favourite, Python 2.3. This is the one
I use in my applications.
Indeed:
With s = '1.0e3333'
IsFloat2(s) returns True
IsFloat1(s) returns True
IsFloat(s) returns False
Note that type(float(s)) is a float:
print type(float(s))
<type 'float'>
but such a value is not very "usefull"
If I need to know if the user has entered a valid integer in a TextCtl,
is use:
def IsInt(s):
try:
if float(s) - int(s) != 0:
return False
else:
return isinstance(int(s), int)
except:
return False
Any comments about the subject is really wellcome.
Jean-Michel Fauth, Switzerland