I'm reading a file into python 2.4 that's structured like this:
field1: 7
field2: "Hello, world!"
field3: 6.2
The idea is to parse it into a dictionary that takes fieldfoo
as the key and whatever comes after the colon as the value.
I want to convert whatever is after the colon to it's "actual" data type, that is, '7'
should be converted to an int
, "Hello, world!"
to a string, etc. The only data types that need to be parsed are ints, floats and strings. Is there a function in the python standard library that would allow one to make this conversion easily?
The only things this should be used to parse were written by me, so (at least in this case) safety is not an issue.
Hope this helps to do what you are trying to do:
First parse your input into a list of pairs like
fieldN: some_string
. You can do this easily withre
module, or probably even simpler with slicing left and right of the indexline.strip().find(': ')
. Then use a literal eval on the valuesome_string
:For older python versions, like the one being asked, the
eval
function can be used but, to reduce evilness, adict
to be the global namespace should be used as second argument to avoid function calls.You can attempt to convert it to an
int
first using the built-in functionint()
. If the string cannot be interpreted as an int aValueError
exception is raised. You can then attempt to convert to afloat
usingfloat()
. If this fails also then just return the initial stringThanks to wim for helping me figure out what I needed to search for to figure this out.
One can just use
eval()
:There is strconv lib.