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

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

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


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


当前回答

str.inumeric()

如果字符串中的所有字符都是数字字符,则返回True,并且至少有一个字符,否则为False。数字字符包括数字字符Unicode数值属性,例如U+2155,VULGAR FRACTION ONE第五。形式上,数字字符是具有属性值的字符Numeric_Type=数字,Numeric_Type=十进制或Numeric_Type=数字。

str.isdecimal()

如果字符串中的所有字符都是十进制字符,并且至少有一个字符,否则为False。十进制字符是可用于在基数10中形成数字的那些,阿拉伯数字零。形式上,十进制字符是一个字符在Unicode通用类别“Nd”中。

两者都适用于Python 3.0中的字符串类型。

其他回答

这不仅丑陋而且缓慢

我对这两个都有异议。

正则表达式或其他字符串解析方法会更丑陋、更慢。

我不确定有什么比上面提到的更快。它调用函数并返回。Try/Catch不会带来太多的开销,因为最常见的异常是在不大量搜索堆栈帧的情况下捕获的。

问题是任何数值转换函数都有两种结果

一个数字,如果该数字有效状态代码(例如,通过errno)或异常,表明无法解析任何有效数字。

C(作为一个例子)通过多种方式解决了这个问题。Python将其清晰明确地展示出来。

我认为你这样做的代码是完美的。

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

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

我也有类似的问题。我想将字符串列表转换为浮点数,而不是定义isNumber函数,这在高级术语中是:

[ float(s) for s in list if isFloat(s)]

在给定的情况下,我们不能真正将float与isFloat函数分开:这两个结果应该由同一个函数返回。此外,如果float失败,整个过程将失败,而不仅仅是忽略错误元素。此外,“0”是一个有效的数字,应包含在列表中。当过滤掉坏元素时,一定不要排除0。

因此,必须以某种方式修改上述理解:

如果列表中的任何元素都无法转换,请忽略它并不要引发异常避免为每个元素多次调用float(一个用于转换,另一个用于测试)如果转换后的值为0,则它仍应出现在最终列表中

我提出了一个以C#的可空数值类型为灵感的解决方案。这些类型在内部由一个结构表示,该结构具有数值,并添加一个布尔值,指示该值是否有效:

def tryParseFloat(s):
    try:
        return(float(s), True)
    except:
        return(None, False)

tupleList = [tryParseFloat(x) for x in list]
floats = [v for v,b in tupleList if b]

使用以下方法处理所有情况:-

import re
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3') 
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '.3')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3sd')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3')

我想看看哪种方法最快。总的来说,check_replace函数给出了最佳和最一致的结果。check_exception函数给出了最快的结果,但前提是没有触发异常——这意味着它的代码是最有效的,但抛出异常的开销非常大。

请注意,检查成功的强制转换是唯一准确的方法,例如,这与check_exception一起工作,但其他两个测试函数将为有效的float返回False:

huge_number = float('1e+100')

以下是基准代码:

import time, re, random, string

ITERATIONS = 10000000

class Timer:    
    def __enter__(self):
        self.start = time.clock()
        return self
    def __exit__(self, *args):
        self.end = time.clock()
        self.interval = self.end - self.start

def check_regexp(x):
    return re.compile("^\d*\.?\d*$").match(x) is not None

def check_replace(x):
    return x.replace('.','',1).isdigit()

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

to_check = [check_regexp, check_replace, check_exception]

print('preparing data...')
good_numbers = [
    str(random.random() / random.random()) 
    for x in range(ITERATIONS)]

bad_numbers = ['.' + x for x in good_numbers]

strings = [
    ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(random.randint(1,10)))
    for x in range(ITERATIONS)]

print('running test...')
for func in to_check:
    with Timer() as t:
        for x in good_numbers:
            res = func(x)
    print('%s with good floats: %s' % (func.__name__, t.interval))
    with Timer() as t:
        for x in bad_numbers:
            res = func(x)
    print('%s with bad floats: %s' % (func.__name__, t.interval))
    with Timer() as t:
        for x in strings:
            res = func(x)
    print('%s with strings: %s' % (func.__name__, t.interval))

以下是2017年MacBook Pro 13上Python 2.7.10的结果:

check_regexp with good floats: 12.688639
check_regexp with bad floats: 11.624862
check_regexp with strings: 11.349414
check_replace with good floats: 4.419841
check_replace with bad floats: 4.294909
check_replace with strings: 4.086358
check_exception with good floats: 3.276668
check_exception with bad floats: 13.843092
check_exception with strings: 15.786169

以下是2017年MacBook Pro 13上Python 3.6.5的结果:

check_regexp with good floats: 13.472906000000009
check_regexp with bad floats: 12.977665000000016
check_regexp with strings: 12.417542999999995
check_replace with good floats: 6.011045999999993
check_replace with bad floats: 4.849356
check_replace with strings: 4.282754000000011
check_exception with good floats: 6.039081999999979
check_exception with bad floats: 9.322753000000006
check_exception with strings: 9.952595000000002

以下是2017年MacBook Pro 13上PyPy 2.7.13的结果:

check_regexp with good floats: 2.693217
check_regexp with bad floats: 2.744819
check_regexp with strings: 2.532414
check_replace with good floats: 0.604367
check_replace with bad floats: 0.538169
check_replace with strings: 0.598664
check_exception with good floats: 1.944103
check_exception with bad floats: 2.449182
check_exception with strings: 2.200056