检查字符串是否可以在 Python 中转换为浮点数 [英] Checking if a string can be converted to float in Python
问题描述
我有一些 Python 代码,可以遍历字符串列表,并在可能的情况下将它们转换为整数或浮点数.对整数执行此操作非常简单
I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy
if element.isdigit():
newelement = int(element)
浮点数更难.现在我正在使用 partition('.')
来分割字符串并检查以确保一侧或两侧都是数字.
Floating point numbers are more difficult. Right now I'm using partition('.')
to split the string and checking to make sure that one or both sides are digits.
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 块中并查看它是否成功,如 这个问题.
This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in this question.
有人有其他想法吗?关于分区和 try/catch 方法的相对优点的意见?
Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?
推荐答案
我会用..
try:
float(element)
except ValueError:
print "Not a float"
..很简单,而且很有效.请注意,如果元素是例如,它仍然会抛出 OverflowError1<<1024.
..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"
这篇关于检查字符串是否可以在 Python 中转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!