Python,确定字符串是否应转换为 Int 或 Float

2024-01-30

我想将字符串转换为最严格的数据类型:int 或 float。

我有两个字符串:

value1="0.80"     #this needs to be a float
value2="1.00"     #this needs to be an integer.

在Python中如何确定value1应该是Float而value2应该是Integer?


def isfloat(x):
    try:
        a = float(x)
    except (TypeError, ValueError):
        return False
    else:
        return True

def isint(x):
    try:
        a = float(x)
        b = int(a)
    except (TypeError, ValueError):
        return False
    else:
        return a == b
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python,确定字符串是否应转换为 Int 或 Float 的相关文章

随机推荐