相关疑难解决方法(0)

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

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

if element.isdigit():
  newelement = int(element)
Run Code Online (Sandbox Code Playgroud)

浮点数更难.现在我正在使用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)
Run Code Online (Sandbox Code Playgroud)

这是有效的,但显然if语句有点像熊.我考虑的另一个解决方案是将转换包装在try/catch块中,看看它是否成功,如本问题所述.

有没有其他想法?关于分区和try/catch方法的相对优点的意见?

python string type-conversion

161
推荐指数
7
解决办法
22万
查看次数

标签 统计

python ×1

string ×1

type-conversion ×1