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.

Chris
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to