在 Python 中检查字符串是否可以表示为数字的最佳方法是什么?

我现在拥有的功能是:

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

这不仅丑陋、缓慢,而且看起来很笨重。但是我还没有找到更好的方法,因为调用 float 在 main 函数中更糟。

有帮助吗?

解决方案

这不仅是丑陋的和缓慢的

我会争端的两个。

Regex或其他串的分析方法将是丑陋和速度较慢。

我不知道什么可以速度快于上述情况。它叫功能并返回。尝试/赶不引入多的开销,因为最常见的例外被抓到没有一个广泛的搜索堆的框架。

问题是,任何数字转换功能有两种结果

  • 一个号码,如果是有效的
  • 一个状态编码(例如,通过errno)或例外显示,有效的数字可以解析。

C(作为一个例子)黑客围绕这一数量的方式。蟒蛇它奠定了出清楚和明确。

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

其他提示

如果你是在寻找解析(正,未签名)整数而不是漂浮,可以使用 isdigit() 功能为串的对象。

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False

串的方法- isdigit(): Python2, Python3

还有东西在Unicode串,我不太熟悉 Unicode-是小数/小数

长话短说 最好的解决办法是 s.replace('.','',1).isdigit()

我做了一些 基准 比较不同的方法

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()

如果字符串不是数字,则 except 块会非常慢。但更重要的是,try- except 方法是唯一正确处理科学记数法的方法。

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)

以下各项不支持浮点表示法“.1234”:
- is_number_regex

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)

以下各项不支持科学记数法“1.000000e+50”:
- is_number_regex
- is_number_repl_isdigit
不支持科学记数法“1e50”:
- is_number_regex
- is_number_repl_isdigit

编辑:基准测试结果

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))

测试了以下功能

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()

enter image description here

有一个例外,你可能要考虑:字符串“男”

如果你想is_number返回FALSE为“男”这个代码将无法正常工作的Python将其转换成其一个数字,是不是数字(谈身份问题)的显示:

>>> float('NaN')
nan

否则,我其实应该感谢你的一段代码,我现在广泛使用的。 :)

-G。

这个怎么样:

'3.14'.replace('.','',1).isdigit()

仅当有一个或没有,这将返回true'。在数字串。

'3.14.5'.replace('.','',1).isdigit()

将返回false

编辑:刚才看到另一条评论... 增加对其他情况下,.replace(badstuff,'',maxnum_badstuff)可以做到的。如果你路过盐,而不是任意的调味品(参考: XKCD#974 )这会做得很好:P

更新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
  

其中,不仅是难看和缓慢的,似乎笨重。

这可能需要一些时间来适应,但是这是做它的Python的方式。如已经指出的那样,选择更糟。但这样做,让一个其他优势:多态性

背后鸭子类型的中心思想是,“如果它走,并像鸭子会谈,那么它就是鸭子。”如果你决定,你需要继承的字符串,这样就可以改变你的决定,如果事情可以被转换成浮动?或者,如果你决定要完全测试一些其他的对象?你可以做这些事情而无需更改上面的代码。

其他的语言解决通过使用接口这些问题。我会保存分析其中的解决方案是另一个线程更好。这一点,虽然,是蟒蛇是决然等式的鸭打字的一面,你可能将不得不习惯语法类似这样的,如果你打算在Python做很多编程(但是,这并不意味着你要像当然它)。

你可能要考虑的另一件事:Python是在抛相比很多其他语言的(超过30倍快的.Net例如)捕获异常非常快。哎呀,语言本身,甚至引发异常沟通无例外的,正常的程序条件(每次使用一个for循环的时间)。因此,直到你看到一个显著的问题,我不会太担心这个代码的性能方面。

有关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

只是模仿C#

C#有两种不同的功能处理分析的标值:

  • 浮动。分析()
  • 浮动。TryParse()

浮动。分析():

def parse(string):
    try:
        return float(string)
    except Exception:
        throw TypeError

注:如果你想知道为什么我改变了例外一种类型错误, 这里的文件.

浮动。try_parse():

def try_parse(string, fail=None):
    try:
        return float(string)
    except Exception:
        return fail;

注:你不想返回布尔'False',因为这仍然是一个值的类型。没有更好,因为它表示失败。当然,如果你想要不同的东西,你可以改变失败的参数为任何你想要的。

延长浮到包括'parse()'和'try_parse()'你会需要monkeypatch的"浮动"类添加这些方法。

如果你想相对于预先存在的职能,该代码应该是这样的:

def monkey_patch():
    if(!hasattr(float, 'parse')):
        float.parse = parse
    if(!hasattr(float, 'try_parse')):
        float.try_parse = try_parse

旁注:我个人喜欢叫它猴冲,因为这感觉就像我滥用的语言,当我这样做,但情况因人而异。

使用:

float.parse('giggity') // throws TypeException
float.parse('54.3') // returns the scalar value 54.3
float.tryParse('twank') // returns None
float.tryParse('32.2') // returns the scalar value 32.2

和伟大的圣人Pythonas说,罗马教廷Sharpisus,"你可以做任何事情我可以做得更好;我可以做任何事情比你更好。"

为串的非号码, try: except: 实际上更慢于普通的表达。为串的有效数字,regex是速度较慢。所以,适当的方法取决于你的输入。

如果你发现你是在绩效结合,可以使用一个新的第三方的模块名为 fastnumbers 这提供了一个函数 isfloat.完全公开,我是作者。我已经包括它的结果在时间如下。


from __future__ import print_function
import timeit

prep_base = '''\
x = 'invalid'
y = '5402'
z = '4.754e3'
'''

prep_try_method = '''\
def is_number_try(val):
    try:
        float(val)
        return True
    except ValueError:
        return False

'''

prep_re_method = '''\
import re
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number_re(val):
    return bool(float_match(val))

'''

fn_method = '''\
from fastnumbers import isfloat

'''

print('Try with non-number strings', timeit.timeit('is_number_try(x)',
    prep_base + prep_try_method), 'seconds')
print('Try with integer strings', timeit.timeit('is_number_try(y)',
    prep_base + prep_try_method), 'seconds')
print('Try with float strings', timeit.timeit('is_number_try(z)',
    prep_base + prep_try_method), 'seconds')
print()
print('Regex with non-number strings', timeit.timeit('is_number_re(x)',
    prep_base + prep_re_method), 'seconds')
print('Regex with integer strings', timeit.timeit('is_number_re(y)',
    prep_base + prep_re_method), 'seconds')
print('Regex with float strings', timeit.timeit('is_number_re(z)',
    prep_base + prep_re_method), 'seconds')
print()
print('fastnumbers with non-number strings', timeit.timeit('isfloat(x)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print('fastnumbers with integer strings', timeit.timeit('isfloat(y)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print('fastnumbers with float strings', timeit.timeit('isfloat(z)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print()

Try with non-number strings 2.39108395576 seconds
Try with integer strings 0.375686168671 seconds
Try with float strings 0.369210958481 seconds

Regex with non-number strings 0.748660802841 seconds
Regex with integer strings 1.02021503448 seconds
Regex with float strings 1.08564686775 seconds

fastnumbers with non-number strings 0.174362897873 seconds
fastnumbers with integer strings 0.179651021957 seconds
fastnumbers with float strings 0.20222902298 seconds

正如你可以看到

  • try: except: 很快的为数字输入,但非常缓慢,对无效的输入
  • regex是非常有效的当输入是无效的
  • fastnumbers 获胜,在这两种情况下

我知道这是特别旧的,但我想补充一个答案,我相信涵盖了信息从最高的投票答案缺少的可能是非常有价值的任何谁找到这样的:

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

x.isdigit() 可以很好地用于检查是否x是整数。

x.replace('-','').isdigit() 可以很好地用于检查是否x是一个负数(检查 - 在第一位置)。

x.replace('.','').isdigit() 可以很好地用于检查是否x是小数。

x.replace(':','').isdigit() 可以很好地用于检查是否x是一个比。

x.replace('/','',1).isdigit() 可以很好地用于检查是否x是一小部分。

铸造浮起并捕捉ValueError异常可能是最快的方法,由于浮子()是专门意味着这一点。其它任何需要字符串解析(正则表达式,等等)可能会比较慢,由于事实,即它不是关注本操作。我的$ 0.02。

您可以使用Unicode字符串,他们有你想要做的只是一个方法:

>>> s = u"345"
>>> s.isnumeric()
True

或者:

>>> s = "345"
>>> u = unicode(s)
>>> u.isnumeric()
True

http://www.tutorialspoint.com/python/string_isnumeric.htm

http://docs.python.org/2/howto/unicode.html

这个答案提供了一步一步的指导具有功能的例子找到串是:

  • 正整数
  • 正/负整数/浮
  • 怎么丢弃"南"(不多)的字符串的同时,检查号码吗?

检查是否符串 积极的 整数

你可以使用 str.isdigit() 检查是否给予串 积极的 整数。

抽样结果:

# 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

如果你想要 此外,检查的 整数和 float, 然后你可以写一个自定义功能检查它为:

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

弃"南"(不多)的字符串的同时,检查号码

上述功能将返回 True 针对"南"(不多)串因为蟒蛇是有效的浮代表它不是一个数字。例如:

>>> is_number('NaN')
True

为了检查次数是否是"南",可以使用 math.isnan() 为:

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

>>> math.isnan(nan_num)
True

或如果你不想进口额外库检查,然后你可以简单地检查它通过比较它本身的使用 ==.蟒蛇返回 Falsenan 浮动与本身。例如:

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

因此,上面的 功能 is_number 可以更新返回 False 对于 "NaN" 为:

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 功能合您的要求。

我想看看该方法是最快的。总体来说,最好的和最一致的结果是由check_replace函数给出。最快的结果是由check_exception函数给出,但前提是没有例外解雇 - 意味着它的代码是最有效的,但抛出异常的开销是相当大的。

请注意,检查一个成功的演员阵容是准确的唯一方法,例如,这一点也适用check_exception但其他两个测试函数将返回False为有效的float:

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))

下面是与Python 2.7.10对结果有2017的MacBook Pro 13:

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

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

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

下面是与PyPy 2.7.13对结果有2017的MacBook Pro 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

因此,为了把它放在一起,检查楠,无穷大,并且复数(这似乎它们其中j指定,而不是I,即,1 + 2J)它导致:

def is_number(s):
    try:
        n=str(float(s))
        if n == "nan" or n=="inf" or n=="-inf" : return False
    except ValueError:
        try:
            complex(s) # for complex
        except ValueError:
            return False
    return True

我做了一些速度测试。可以说,如果串 有可能的 是一个量的 尝试/除外 战略是最快的可能。如果串 不可能的 是一个数字 你有兴趣 整数 检查,这值得去做一些测试(isdigit加上标题'-').如果你有兴趣检查浮动数量,必须使用的 尝试/除外 代码没装配加载静逃脱。

我需要确定一个字符串浇铸成基本类型(浮动,INT,STR,布尔)。在互联网上没有找到任何东西后,我创造了这个:

def str_to_type (s):
    """ Get possible cast type for a string

    Parameters
    ----------
    s : string

    Returns
    -------
    float,int,str,bool : type
        Depending on what it can be cast to

    """    
    try:                
        f = float(s)        
        if "." not in s:
            return int
        return float
    except ValueError:
        value = s.upper()
        if value == "TRUE" or value == "FALSE":
            return bool
        return type(s)

实施例

str_to_type("true") # bool
str_to_type("6.0") # float
str_to_type("6") # int
str_to_type("6abc") # str
str_to_type(u"6abc") # unicode       

可以捕捉的类型和使用它

s = "6.0"
type_ = str_to_type(s) # float
f = type_(s) 

该输入可以是如下所示:

a="50" b=50 c=50.1 d="50.1"


1总输入:

该函数的输入可以是一切!

求给定变量是否是数字。数字化字符串包含可选的符号,任意数量的数字,可选的小数部分和可选的指数部分的。因此+ 0123.45e6是一个有效的数值。十六进制(例如0xf4c3b00c)和二进制(例如0b10100111001)符号是不允许的。

<强> is_numeric 功能

import ast
import numbers              
def is_numeric(obj):
    if isinstance(obj, numbers.Number):
        return True
    elif isinstance(obj, str):
        nodes = list(ast.walk(ast.parse(obj)))[1:]
        if not isinstance(nodes[0], ast.Expr):
            return False
        if not isinstance(nodes[-1], ast.Num):
            return False
        nodes = nodes[1:-1]
        for i in range(len(nodes)):
            #if used + or - in digit :
            if i % 2 == 0:
                if not isinstance(nodes[i], ast.UnaryOp):
                    return False
            else:
                if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                    return False
        return True
    else:
        return False

试验:

>>> is_numeric("54")
True
>>> is_numeric("54.545")
True
>>> is_numeric("0x45")
True

<强> is_float 功能

求给定变量是否为浮动。浮子串包括可选符号的,任意数量的数字,...

import ast

def is_float(obj):
    if isinstance(obj, float):
        return True
    if isinstance(obj, int):
        return False
    elif isinstance(obj, str):
        nodes = list(ast.walk(ast.parse(obj)))[1:]
        if not isinstance(nodes[0], ast.Expr):
            return False
        if not isinstance(nodes[-1], ast.Num):
            return False
        if not isinstance(nodes[-1].n, float):
            return False
        nodes = nodes[1:-1]
        for i in range(len(nodes)):
            if i % 2 == 0:
                if not isinstance(nodes[i], ast.UnaryOp):
                    return False
            else:
                if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                    return False
        return True
    else:
        return False

试验:

>>> is_float("5.4")
True
>>> is_float("5")
False
>>> is_float(5)
False
>>> is_float("5")
False
>>> is_float("+5.4")
True

什么是 AST


2-如果确信该变量内容的字符串

使用 str.isdigit()方法

>>> a=454
>>> a.isdigit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isdigit'
>>> a="454"
>>> a.isdigit()
True

3-数值输入:

<强>检测int值:

>>> isinstance("54", int)
False
>>> isinstance(54, int)
True
>>> 

<强>检测浮动:

>>> isinstance("45.1", float)
False
>>> isinstance(45.1, float)
True

RyanN表明

  

如果要为为NaN和INF,变更线为x =浮子(多个)返回False;返程(X = = X)和(x - 1 = X)。这应该只是天道酬勤和NaN的所有彩车返回True

但是,这完全不是那么回事,因为足够大的浮动,x-1 == x返回true。例如,2.0**54 - 1 == 2.0**54

我认为您的解决方案是好的。

话虽如此,有很多的正则表达式的仇恨对这些问题的答案,我认为是不合理的,正则表达式可以合理的清洁和正确和快速。这真的取决于你想要做什么。原来的问题是你怎么能“检查是否字符串可以表示为一个号码(浮动)”(根据您的标题)。想必你想使用数字/浮点值,一旦你已经检查了它是有效的,在这种情况下,你的try /除了让有很大的意义。但是,如果由于某种原因,你只是想验证一个的字符串的是数量的再一个正则表达式也能正常工作,但它很难得到正确的。我想大多数的正则表达式的答案到目前为止,例如,不正确地解析没有整数部分字符串(如。” 7" ),这是一个浮动至于蟒蛇而言。而这一点技巧在不需要小数部分的单一的正则表达式来检查。我已经包括两名正则表达式来显示这一点。

它确实提出一个有趣的问题,什么是“数字”的说法。你有“INF”,这是作为Python中的浮动有效?或者你包括是“数字”,但也许不能在python来表示的数字(如那些比浮子max的情况下的数字)。

还有你如何解析数字模糊。例如,什么是“--20”?这是一个“数字”?这是代表“20”一个合法的方式? Python将让你做“VAR = --20”并将其设置为20(但实际上,这是因为它把它作为一个表达式),但是浮动。(“ - 20”)不工作

不管怎么说,没有更多的信息,下面是我认为一个正则表达式涵盖了所有的整型和浮点的为Python解析它们的。

# Doesn't properly handle floats missing the integer part, such as ".7"
SIMPLE_FLOAT_REGEXP = re.compile(r'^[-+]?[0-9]+\.?[0-9]+([eE][-+]?[0-9]+)?$')
# Example "-12.34E+56"      # sign (-)
                            #     integer (12)
                            #           mantissa (34)
                            #                    exponent (E+56)

# Should handle all floats
FLOAT_REGEXP = re.compile(r'^[-+]?([0-9]+|[0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?$')
# Example "-12.34E+56"      # sign (-)
                            #     integer (12)
                            #           OR
                            #             int/mantissa (12.34)
                            #                            exponent (E+56)

def is_float(str):
  return True if FLOAT_REGEXP.match(str) else False

一些示例性测试值:

True  <- +42
True  <- +42.42
False <- +42.42.22
True  <- +42.42e22
True  <- +42.42E-22
False <- +42.42e-22.8
True  <- .42
False <- 42nope

我还用你所提到的功能,但很快我发现字符串作为“南”,“天道酬勤”和它的变化被认为是数。所以,我建议你提高你的函数的版本,将返回这些类型的输入错误,并不会失败“1E3”变种:

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

此代码处理的指数,浮筒,和整数,而无需使用正则表达式。

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

下面是我做这件事的简单方法。比方说,我通过一些字符串循环,我想将它们添加到一个数组,如果他们变成是数字。

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

替换任何你想要的操作与弦做的,如果它原来是一个数字的myvar.apppend。我们的想法是尝试使用浮动()操作,并使用返回的错误以确定该字符串是否是一个数字。

您可以通过返回比真和假更多有用的值概括在一个有用的方法之外的技术。例如该函数将引号一轮串而是独自离开的数字。这是我需要的一个快速和肮脏的过滤器,以使对R.一些变量定义

import sys

def fix_quotes(s):
    try:
        float(s)
        return s
    except ValueError:
        return '"{0}"'.format(s)

for line in sys.stdin:
    input = line.split()
    print input[0], '<- c(', ','.join(fix_quotes(c) for c in input[1:]), ')'

我工作,导致我这个线程的一个问题,即如何对数据字符串和数字的集合转换以最直观的方式。我读原代码,我需要在两个方面是不同的后恍然大悟:

1 - 我想的整数结果,如果该字符串表示的整数

2 - 我想要一个数字或字符串结果粘到数据结构

,所以我适于原码,以产生该衍生物:

def string_or_number(s):
    try:
        z = int(s)
        return z
    except ValueError:
        try:
            z = float(s)
            return z
        except ValueError:
            return s

尝试。

 def is_number(var):
    try:
       if var == int(var):
            return True
    except Exception:
        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)])

使用下列它处理所有的情况下: -

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')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top