有没有办法在python中找到字符串中的值是否为浮点数?

问题描述

我对字符串有问题,我知道使用 isdigit() 我们可以找到字符串中的整数是否为 int,但如何找到它在字符串中的浮点数。我也用过 isinstance() 虽然它没有用。在字符串中查找值的任何其他替代方法是否为浮点数??

我的代码

v = '23.90'
isinstance(v,float)

给出:

False

异常输出

True

解决方法

您可以将其强制转换为 float 或 int,然后捕获最终的异常,如下所示:

try:
    int(val)
except:
    print("Value is not an integer.")
try:
    float(val)
except:
    print("Value is not a float.")

您可以在 False 部分返回 except,并在 True 部分的演员表之后返回 try,如果这是您想要的。

,

也许你可以试试这个

def in_float_form(inp):
   can_be_int = None
   can_be_float = None
   try:
      float(inp)
   except:
      can_be_float = False
   else:
      can_be_float = True
   try:
      int(inp)
   except:
      can_be_int = False
   else:
      can_be_int = True
   return can_be_float and not can_be_int
In [4]: in_float_form('23')
Out[4]: False

In [5]: in_float_form('23.4')
Out[5]: True
,

您可以通过isdigit()检查数字是否为整数,并根据此返回值。

s = '23'

try:
    if s.isdigit():
        x = int(s)
        print("s is a integer")
    else:
        x = float(s)
        print("s is a float")
except:
    print("Not a number or float")
,

一个非常简单的方法是将其转换为浮点数,然后再次转换回字符串,然后将其与原始字符串进行比较 - 如下所示:

v = '23.90'
try:
    if v.rstrip('0') == str(float(v)).rstrip('0'):
        print("Float")
    else:
        print("Not Float")
except:
    print("Not Float!")