While working on one of my projects, I found myself having to typecast all the elements in a list into their appropriate data type. To give more prespective.
1
|
|
I wanted them to be converted into an int,float and string as opposed to all strings. One of the hacky ways would be to use a regular expression to match the digits and type cast them.
However, It is not elegant and the regular expression may or may not cover all the cases. That set me thinking as to what would the idiomatic way to do such hierarchial casting.
Here is what I did.
- First tries to convert it to int.
- If the attempt to convert to int fails then it tries float, even if that fails it returns the actual string.
It is one of the nicities of python that it allows excepts to be passed, i.e the interpreter simply ignores the exception and moves on to the next instruction.