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

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

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


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


当前回答

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

其他回答

这是我的简单方法。假设我在循环一些字符串,如果它们变成数字,我想将它们添加到数组中。

try:
    myvar.append( float(string_to_check) )
except:
    continue

如果myvar.apppend是一个数字,则将其替换为要对字符串执行的任何操作。其想法是尝试使用float()操作,并使用返回的错误来确定字符串是否为数字。

强制转换为float并捕获ValueError可能是最快的方法,因为float()专门用于此。任何其他需要字符串解析(正则表达式等)的操作都可能会比较慢,因为它没有针对该操作进行调整。我的0.02美元。

我知道这是一个特别古老的问题,但我想补充一个答案,我相信这个答案涵盖了投票最高的答案中缺少的信息,对任何发现这一点的人来说都非常有价值:

对于以下每个方法,如果需要接受任何输入,请将它们与计数连接。(假设我们使用的是整数的语音定义,而不是0-255等)

x.isdigit()用于检查x是否为整数。

x.replace('-','').idigit()用于检查x是否为负值。(值机柜台第一位)

x.replace('.','').idigit()用于检查x是否为小数。

x.replace(“:”,“”).idigit()用于检查x是否为比率。

x.replace('/','',1).idigit()用于检查x是否为分数。

import re
def is_number(num):
    pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
    result = pattern.match(num)
    if result:
        return True
    else:
        return False


​>>>: is_number('1')
True

>>>: is_number('111')
True

>>>: is_number('11.1')
True

>>>: is_number('-11.1')
True

>>>: is_number('inf')
False

>>>: is_number('-inf')
False

在浮点数的最常见情况下,我们希望处理整数和小数。让我们以字符串“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)