有理数的isDigit()?
我想检查我界面上一个文本框里的内容是不是数字(也就是说,不是文字或其他东西)。在Python里,有一个叫做isdigit()的方法,如果这个字符串只包含数字(没有负号或小数点),它会返回True。那有没有其他方法可以判断我的字符串是不是一个有理数(比如:1.25)呢?
示例代码:
if self.components.txtZoomPos.text.isdigit():
step = int(self.components.txtZoomPos.text)
5 个回答
1
现有的回答是对的,通常更符合Python风格的方法是使用try...except
(也就是EAFP)。
不过,如果你真的想要进行验证,可以在使用isdigit()
之前,先去掉一个小数点。
>>> "124".replace(".", "", 1).isdigit()
True
>>> "12.4".replace(".", "", 1).isdigit()
True
>>> "12..4".replace(".", "", 1).isdigit()
False
>>> "192.168.1.1".replace(".", "", 1).isdigit()
False
需要注意的是,这样做对浮点数和整数的处理是一样的。如果你真的需要区分这两者,可以加上相应的检查。
1
在Python中,try
/catch
的使用成本非常低,也就是说,使用它不会消耗太多资源。如果你尝试从一个不是数字的字符串中创建一个float
(浮点数),就会出现一个错误(也叫异常)。
>>> float('1.45')
1.45
>>> float('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): foo
你可以这样做:
try:
# validate it's a float
value = float(self.components.txtZoomPos.text)
except ValueError, ve:
pass # your error handling goes here
5
1.25 是一个常用的表示方式,主要用于表示实数,较少用于有理数。Python 中的 float 类型在转换失败时会抛出一个 ValueError 错误。因此:
def isReal(txt):
try:
float(txt)
return True
except ValueError:
return False