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

标签 python string type-conversion

我有一些 Python 代码可以遍历字符串列表,并尽可能将它们转换为整数或 float 。对整数执行此操作非常简单

if element.isdigit():
  newelement = int(element)

float 更难。现在我正在使用 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 block 中并查看它是否成功,如 this question 中所述。 .

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

最佳答案

我会用..

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

..它很简单,而且很有效。请注意,如果元素是例如它仍然会抛出溢出错误。 1<<1024.

另一种选择是正则表达式:

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

关于python - 检查字符串是否可以在 Python 中转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/736043/

相关文章:

c++ - 如何在 C++ 中返回 foreach 循环的值?

c - 设置字符串为 NULL

Golang 类型在指向一种类型 slice 的指针 slice 与另一种类型 slice 之间的类型转换

python - 使用 Python 3 的平均年龄计算器

python - 替换字符串中一组字符的最快方法

python - NoReverseMatch 使用反向和带参数的 url

c++ - 哪种类型的指针用于字节解析?

c - gtk+: print a float value to an entry widget

python - PyQt4 使用 setRowHidden 在 QListView 上按文本进行过滤

python - 通过嵌套字典键获取唯一列表项