如何在Python中检查字符串是否表示数值?

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

上述方法可行,但似乎很笨拙。


如果您正在测试的内容来自用户输入,那么即使它表示int或float,它仍然是一个字符串。请参阅如何将输入读取为数字?用于转换输入,并询问用户输入,直到他们给出有效响应以确保输入在继续之前表示int或float(或其他要求)。


当前回答

我做了一些速度测试。让我们假设,如果字符串可能是一个数字,则try/except策略是最快的。如果字符串不可能是数字,并且您对整数检查感兴趣,则值得进行一些测试(isdigit加上标题“-”)。如果您有兴趣检查浮点数,则必须使用try/except代码而不进行转义。

其他回答

在Alfe指出您不需要单独检查浮点数后更新,因为两者都是复杂的句柄:

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True

之前说过:在一些罕见的情况下,您可能还需要检查复数(例如1+2i),这不能用浮点数表示:

def is_number(s):
    try:
        float(s) # for int, long and float
    except ValueError:
        try:
            complex(s) # for complex
        except ValueError:
            return False

    return True

这段代码处理指数、浮点数和整数,不使用正则表达式。

return True if str1.lstrip('-').replace('.','',1).isdigit() or float(str1) else False

用户助手功能:

def if_ok(fn, string):
  try:
    return fn(string)
  except Exception as e:
    return None

然后

if_ok(int, my_str) or if_ok(float, my_str) or if_ok(complex, my_str)
is_number = lambda s: any([if_ok(fn, s) for fn in (int, float, complex)])

在浮点数的最常见情况下,我们希望处理整数和小数。让我们以字符串“1.1”为例。

我会尝试以下方法之一:

1.>isnumeric()

word = "1.1"

"".join(word.split(".")).isnumeric()
>>> True

2.>isdigit()

word = "1.1"

"".join(word.split(".")).isdigit()
>>> True

3.>isdecimal()

word = "1.1"

"".join(word.split(".")).isdecimal()
>>> True

速度:

► 所有上述方法具有相似的速度。

%timeit "".join(word.split(".")).isnumeric()
>>> 257 ns ± 12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit "".join(word.split(".")).isdigit()
>>> 252 ns ± 11 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit "".join(word.split(".")).isdecimal()
>>> 244 ns ± 7.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

该答案提供了一步一步的指导,具有查找字符串的示例:

正整数正/负-整数/浮点如何在检查数字时丢弃“NaN”(不是数字)字符串?

检查字符串是否为正整数

您可以使用str.idigit()检查给定的字符串是否为正整数。

样本结果:

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

检查字符串是否为正/负-整数/浮点

如果字符串是负数或浮点数,str.isdigit()返回False。例如:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

如果您还想检查负整数和浮点数,那么您可以编写一个自定义函数来检查它,如下所示:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

样品运行:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

检查数字时放弃“NaN”(非数字)字符串

上述函数将为“NAN”(非数字)字符串返回True,因为对于Python,它是表示它不是数字的有效浮点数。例如:

>>> is_number('NaN')
True

为了检查数字是否为“NaN”,可以使用math.isnan()作为:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

或者,如果您不想导入其他库来检查它,那么您可以通过使用==将其与自身进行比较来检查它。当nan float与自身比较时,Python返回False。例如:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

因此,上述函数is_number可以更新为“NaN”返回False,如下所示:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

样品运行:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

PS:根据号码类型,每次检查的每次操作都会产生额外的开销。选择符合您需求的is_number函数版本。