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

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

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


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


当前回答

def is_float(s):
    if s is None:
        return False

    if len(s) == 0:
        return False

    digits_count = 0
    dots_count = 0
    signs_count = 0

    for c in s:
        if '0' <= c <= '9':
            digits_count += 1
        elif c == '.':
            dots_count += 1
        elif c == '-' or c == '+':
            signs_count += 1
        else:
            return False

    if digits_count == 0:
        return False

    if dots_count > 1:
        return False

    if signs_count > 1:
        return False

    return True

其他回答

在浮点数的最常见情况下,我们希望处理整数和小数。让我们以字符串“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”、“Inf”及其变体被视为数字。因此,我建议您改进函数的版本,该版本将在这些类型的输入上返回false,并且不会失败“1e3”变体:

def is_float(text):
    try:
        float(text)
        # check for nan/infinity etc.
        if text.isalpha():
            return False
        return True
    except ValueError:
        return 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)])

对于我非常简单和常见的用例:这个用键盘书写的字符串是数字吗?

我通读了大部分答案,最后得到了:

def isNumeric(string):
    result = True
    try:
        x = float(string)
       result = (x == x) and (x - 1 != x)
    except ValueError:
        result = False
    return result

对于(+/-)NaN和(+-)inf,它将返回False。

你可以在这里查看:https://trinket.io/python/ce32c0e54e

对于int,请使用以下命令:

>>> "1221323".isdigit()
True

但对于float,我们需要一些技巧;-)。每个浮点数都有一个点。。。

>>> "12.34".isdigit()
False
>>> "12.34".replace('.','',1).isdigit()
True
>>> "12.3.4".replace('.','',1).isdigit()
False

对于负数,只需添加lstrip():

>>> '-12'.lstrip('-')
'12'

现在我们有了一个通用的方法:

>>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
True
>>> '.-234'.lstrip('-').replace('.','',1).isdigit()
False