tags:

views:

643

answers:

4

I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another way I could evaluate if my string is a rational number (ex: 1.25).

Example code:

if self.components.txtZoomPos.text.isdigit():
        step = int(self.components.txtZoomPos.text)
A: 

int() or float() throws ValueError if the literal is not valid

dfa
A: 

float() throws a ValueError if the conversion fails. So try to convert your string to a float, and catch the ValueError.

user9876
+3  A: 

1.25 is a notation commonly used for reals, less so for rational numbers. Python's float will raise a ValueError when conversion fails. Thus:

def isReal(txt):
    try:
        float(txt)
        return True
    except ValueError:
        return False
Stephan202
No, it's both, if you go by the standard maths names. The real number line consists of the rational numbers and irrational numbers, the rational number line is the integers and numbers that can be represented in the form 'a/b' where a and b are integers.
workmad3
@workmad3: you're right, which is why I quickly updated my answer (but unfortunately after you saw it ;) )
Stephan202
+1, I was just typing up the same thing when your answer appeared. Darn! Missed the rep points!
PTBNL
+1  A: 

try/catch is very cheap in Python, and attempting to construct a float from a string that's not a number raises an exception:

>>> float('1.45')
1.45
>>> float('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): foo

You can just do something like:

try:
    # validate it's a float
    value = float(self.components.txtZoomPos.text)
except ValueError, ve:
    pass # your error handling goes here
Paul Fisher