我有一些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方法的相对优点有什么看法?
发布于 2014-01-05 11:56:53
用于检查浮动的Python方法:
def is_float(element: Any) -> bool:
try:
float(element)
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 interpretedhttps://stackoverflow.com/questions/736043
复制相似问题