isDigit()是否有理数?

JcM*_*aco 4 python string

我试图评估我的界面的一个文本框中的字符串是否是一个数字(即不是文本或其他任何东西).在Python中,有一个名为isdigit()的方法,如果字符串只包含数字(没有负号或小数点),则返回True.如果我的字符串是一个有理数字(ex:1.25),还有另一种方法可以评估.

示例代码:

if self.components.txtZoomPos.text.isdigit():
        step = int(self.components.txtZoomPos.text)
Run Code Online (Sandbox Code Playgroud)

Ste*_*202 5

1.25是一种常用于实数的符号,对于有理数而言则较少.当转换失败时,Python的float会引发ValueError.从而:

def isReal(txt):
    try:
        float(txt)
        return True
    except ValueError:
        return False
Run Code Online (Sandbox Code Playgroud)