👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
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)
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.isdigit() and partition == "." and partition.isdigit()) or (partition == "" and partition == "." and partition.isdigit()) or (partition.isdigit() and partition == "." and partition == ""): newelement = float(element)
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.
Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?
👻 Read also: what is the best laptop for engineering students?