[Tutor] Quick way to find the data type
dyoo at hkn.eecs.berkeley.edu
Tue Sep 27 22:04:34 CEST 2005
> A quick way, yes. But also secure? No.
> >>> l = ['false', 'True', '3', '1.394']
> >>> l = [eval(x) for x in l]
> >>> print l
> [False, True, 3, 1.3939999999999999]
> but this fails when it encounters a string that eval can't handle, for
> example 'false'. Also eval will evaluate any valid Pythin expression in
> the string, so you should use it only when you know *exactly* that the
> string can not contain anything harmful. Which is rarely the case.
Yeah, I also strongly discourage eval() here: it's very dangerous. And
even if its weren't dangerous, for the particular job of doing data
conversion from strings to values, it's still probably the wrong tool,
since it doesn't allow for any kind of customization.
We know eval() is both dangerous and uncustomizable, so that makes it all
the more worthwhile to avoid it like the plague. *grin* Don't use it for
data parsing and conversion.
Kent's link to Paul McGuire's solution sounds like a straightforward way
to do the string processing: it's controlled, and can be easily modified
to handle specialized literals like lowercased 'true' or 'false'.
"Lexers" are a more specialized class of tools for doing this sort of
thing, and there are several of them out there for Python.
More information about the Tutor