在不使用 try/except 的情况下检查 Python 字符串是否为数字的最简单方法?

Easiest way to check if a Python string is a number without using try/except?

所以我有一个 Python 脚本可以进行大量计算,但有时传递到公式中的“数字”并不总是数字。有时它们是字符串。

基本上,编写这些代码行的更简单方法是什么:

        units = 0 if math.isnan(UNITS) else OPH_UNITS
        # the rate here could be "N/A" so the line below fails with: must be real number, not str
        rate = 0 if not rate else rate
        total = total + ((rate * units) * factor)

所以我已经有一个检查,如果速率为 None,则使 rate 的值为 0,但如果值为“N/A”或任何其他值,则仍然会失败那不是一个数字。在没有 try/except 的情况下进行此计算的 Pythonic 方法是什么,以便 rate 可以是任何值,只要 rate 是某个数字,计算就可以进行?

有一个名为 isnumeric() 的方法,您可以在字符串上调用该方法;请在此处查看 documentation。它 returns True 如果所有字符都是数字(数字或其他具有数值的 Unicode 字符,例如分数),否则 False。但我个人最喜欢的仍然是 try/except,类型转换为 intfloat

您可以检查 None、实例和 number-like 字符串:

if not rate or not str(rate).replace(".", "").isnumeric():
    rate = 0
elif isinstance(rate, str):
    if rate.isnumeric():
        rate = int(rate)
    elif rate.replace(".", "").isnumeric():
        rate = float(rate)

测试table

rate output type
'test' 0 <class 'int'>
'test123' 0 <class 'int'>
'123' 123 <class 'int'>
None 0 <class 'int'>
False 0 <class 'int'>
123 123 <class 'int'>
'1.1/1' 0 <class 'int'>
complex(1, 1) 0 <class 'int'>
'1.1' 1.1 <class 'float'>
1.1 1.1 <class 'float'>

如果您严格转换为 intfloats0):

if not rate or not str(rate).isnumeric():
    rate = 0
elif isinstance(rate, str):
    rate = int(rate)

如果您想将 float 舍入为 int:

if not rate:
    rate = 0
elif isinstance(rate, str):
    rate = int(float(rate))

总的来说,这并不能说明一切。如评论中所述,'½' (U+00BD) unicode 将是 True for .isnumeric()。这会破坏程序。

您可以手动为所有输入添加例外,但建议只使用 tryexcept。不要尝试 一行 或在缺少功能时为了美观而简化表达式。