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

检查字符串是否可以在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方法的相对优点的意见?


翻过高山走不出你
浏览 1820回答 3
3回答

ibeautiful

我会用...try:     float(element)except ValueError:     print "Not a float"..它很简单,而且很有效另一种选择是正则表达式:import reif re.match("^\d+?\.\d+?$", element) is None:     print "Not float"

慕斯709654

'1.43'.replace('.','',1).isdigit()true只有在有'或'的情况下才会返回。在数字串中。 '1.4.3'.replace('.','',1).isdigit()将返回 false '1.ww'.replace('.','',1).isdigit()将返回 false
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python