检查字符串是否可以在Python中转换为float我有一些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块中,看看它是否成功,如本问题所述。有没有其他想法?关于分区和try / catch方法的相对优点的意见?
3 回答

ibeautiful
TA贡献1993条经验 获得超5个赞
我会用...
try: float(element)except ValueError: print "Not a float"
..它很简单,而且很有效
另一种选择是正则表达式:
import reif re.match("^\d+?\.\d+?$", element) is None: print "Not float"

慕斯709654
TA贡献1840条经验 获得超5个赞
'1.43'.replace('.','',1).isdigit()
true
只有在有'或'的情况下才会返回。在数字串中。
'1.4.3'.replace('.','',1).isdigit()
将返回 false
'1.ww'.replace('.','',1).isdigit()
将返回 false
添加回答
举报
0/150
提交
取消