【问题标题】:Is there built-in way to check if string can be converted to float?是否有内置方法来检查字符串是否可以转换为浮点数?
【发布时间】:2021-01-28 08:56:39
【问题描述】:

我知道有一些方法可以检查 str 是否可以使用 try-except 或正则表达式进行转换,但我正在寻找(例如)str 方法,例如

str.isnumeric()
str.isdigit()
str.isdecimal() # also doesn't work for floats

但找不到。 有没有我还没找到的?

【问题讨论】:

标签: python string type-conversion double


【解决方案1】:

最简单的方法就是试着把它变成一个浮点数。

try:
    float(str)
except ValueError:
    # not float
else:
    # is float

【讨论】:

    【解决方案2】:

    我建议使用 try except 子句的请求宽恕而不是许可的方法:

    str_a = 'foo'
    str_b = '1.2'
    
    def make_float(s):
        try:
            return float(s)
        except ValueError:
            return f'Can't make float of "{s}"'
    

    >>> make_float(str_a)
    Can't make float of "foo"
    >>> make_float(str_b)
    1.2
    

    【讨论】:

    • 当然。这就是 Python 方式。来自 Python 词汇表:“请求宽恕比请求许可更容易。这种常见的 Python 编码风格假设存在有效的键或属性,如果假设被证明是错误的,则捕获异常。这种简洁快速的风格的特点是存在许多尝试和除了语句。该技术与许多其他语言(例如 C)常见的 LBYL 样式形成对比。”
    【解决方案3】:

    如和MacattackJab 所述,您可以使用try except,您可以在python's docsw3school's tutorial 中阅读。

    Try except 子句的形式为:

    try:
        # write your code
        pass
    except Exception as e: # which can be ValueError, or other's exceptions
        # deal with Exception, and it can be called using the variable e
        print(f"Exception was {e}") # python >= 3.7
        pass
    except Exception as e: # for dealing with other Exception
        pass
    # ... as many exceptions you would need to handle
    finally:
        # do something after dealing with the Exception
        pass
    

    有关内置异常的列表,请参阅python's docs

    【讨论】:

      猜你喜欢
      • 2010-12-28
      • 2010-10-18
      • 2022-10-15
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2012-09-10
      • 2011-07-26
      • 2018-07-08
      相关资源
      最近更新 更多