在Python中检查字符串是否可以转换为float

2024-04-25 00:26:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些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块中,看看它是否成功,如this question所述。

有人有其他想法吗?对分区和try/catch方法的相对优点的看法?


Tags: orand字符串代码列表if整数element
3条回答
'1.43'.replace('.','',1).isdigit()

只有当数字串中有一个或没有“.”时,它才会返回true

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

将返回false

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

将返回false

检查float的Python方法:

def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False

别被藏在浮船上的妖精咬了!做单元测试!

什么是浮子,什么不是浮子可能会让你吃惊:

Command to parse                        Is it a float?  Comment
--------------------------------------  --------------- ------------
print(isfloat(""))                      False
print(isfloat("1234567"))               True 
print(isfloat("NaN"))                   True            nan is also float
print(isfloat("NaNananana BATMAN"))     False
print(isfloat("123.456"))               True
print(isfloat("123.E4"))                True
print(isfloat(".1"))                    True
print(isfloat("1,234"))                 False
print(isfloat("NULL"))                  False           case insensitive
print(isfloat(",1"))                    False           
print(isfloat("123.EE4"))               False           
print(isfloat("6.523537535629999e-07")) True
print(isfloat("6e777777"))              True            This is same as Inf
print(isfloat("-iNF"))                  True
print(isfloat("1.797693e+308"))         True
print(isfloat("infinity"))              True
print(isfloat("infinity and BEYOND"))   False
print(isfloat("12.34.56"))              False           Two dots not allowed.
print(isfloat("#56"))                   False
print(isfloat("56%"))                   False
print(isfloat("0E0"))                   True
print(isfloat("x86E0"))                 False
print(isfloat("86-5"))                  False
print(isfloat("True"))                  False           Boolean is not a float.   
print(isfloat(True))                    True            Boolean is a float
print(isfloat("+1e1^5"))                False
print(isfloat("+1e1"))                  True
print(isfloat("+1e1.3"))                False
print(isfloat("+1.3P1"))                False
print(isfloat("-+1"))                   False
print(isfloat("(1)"))                   False           brackets not interpreted

我会用。。

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

…很简单,而且很有效

另一个选项是正则表达式:

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

相关问题 更多 >