[Tutor] Quick way to find the data type
3dbernard at gmail.com
Tue Sep 27 22:06:30 CEST 2005
Thanks a lot Chris.
On 9/27/05, Christopher Arndt <chris.arndt at web.de> wrote:
> Bernard Lebel schrieb:
> > Hello,
> > Let say I have a string. The value of the string might be 'False',
> > 'True', '3', '1.394', or whatever else. Is there a quick way to
> > convert this string into the appropriate data type other than with
> > try/except?
> 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.
> Tutor maillist - Tutor at python.org
More information about the Tutor