且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查字符串是否可以在 Python 中转换为浮点数

更新时间:2023-11-28 18:16:40

我会用..

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

..很简单,而且很有效.请注意,如果元素是例如,它仍然会抛出 OverflowError1

..it's simple, and it works. Note that it will still throw OverflowError if element is e.g. 1<<1024.

另一个选项是正则表达式:

Another option would be a regular expression:

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