我有一些Python代码,它运行一个字符串列表,并将它们转换为整数或浮点数(如果可能的话)。对整数执行此操作非常简单

if element.isdigit():
  newelement = int(element)

浮点数比较难。现在我正在使用partition('.')来分割字符串,并检查以确保一侧或两侧都是数字。

partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit()) 
    or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit()) 
    or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
  newelement = float(element)

这是可行的,但显然if语句有点麻烦。我考虑的另一个解决方案是将转换封装在一个try/catch块中,看看它是否成功,如这个问题所述。

有人有其他想法吗?对分区和尝试/捕获方法的相对优点有什么看法?


当前回答

这个正则表达式将检查科学浮点数:

^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$

但是,我认为最好的办法是尝试使用解析器。

其他回答

我会用。

try:
    float(element)
except ValueError:
    print "Not a float"

..这很简单,也很有效。注意,如果元素是例如1<<1024,它仍然会抛出OverflowError。

另一种选择是正则表达式:

import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
    print "Not float"

如果你不需要担心科学或其他数字的表达式,并且只处理可以是带句号或不带句号的数字的字符串:

函数

def is_float(s):
    result = False
    if s.count(".") == 1:
        if s.replace(".", "").isdigit():
            result = True
    return result

Lambda版本

is_float = lambda x: x.replace('.','',1).isdigit() and "." in x

例子

if is_float(some_string):
    some_string = float(some_string)
elif some_string.isdigit():
    some_string = int(some_string)
else:
    print "Does not convert to int or float."

这样你就不会意外地将一个int型转换为浮点型。

函数is_digit(str)的简化版本,它在大多数情况下都足够了(不考虑指数符号和“NaN”值):

def is_digit(str):
    return str.lstrip('-').replace('.', '').isdigit()

我找到了一个同样有效的方法。需要核实这一点。第一次在这里放东西。

def isfloat(a_str):
    try:
        x=float(a_str)
        if x%1 == 0:
            return False
        elif x%1 != 0: #an else also do
            return True
    except Exception as error:
            return False

我们可以使用regex作为: 进口再保险 如果re.match([0 - 9] *。?[0 - 9] +”,< your_string >): print(“它是一个浮点数/int”) 其他: 打印(“这是外星的东西”) 让我用英语解释一下正则表达式,

* -> 0次或更多次 + -> 1次或以上 ? -> 0/1发生

现在,让我们进行转换

'[0-9]* ->允许在0-9之间出现0个或多个数字 \。->后面跟着0或1 '。'(如果你需要检查它是否可以是int/float,否则我们也可以使用?,使用{1}) [0-9]+ ->后跟0个或多个0-9之间的数字