[PYTHON DB-SIG] Converting strings to numbers

Hal J Schechner hal-j@alpha.netusa.net
Wed, 23 Oct 1996 05:19:05 -0400 (EDT)


On Tue, 22 Oct 1996, Karen Savage wrote:

> This seems like it should be easy to do, but I can't figure it out.  I have
> a string variable containing a numeric value. (i.e. '3').  I want to convert
> it to a numeric variable type.  Any ideas?  Also is there an equivalent of
> an IsNumber(string) call that tells you if a string value can be converted
> to a numeric?
> 

This can not only be done from string reps of a number to a numeric type, 
but also from string reps of anything (lists, tuples, dicts etc..) to thier
actual type. ( nice for reading plaintext datafiles ). 

example:

Python 1.3 (Oct 13 1996)  [GCC 2.7.2]
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> foo = '3.14159'
>>> foo
'3.14159'
>>> bar = eval(foo)
>>> bar
3.14159
>>> bar + 1.0
4.14159
>>>
>>> Foo = '[1,2,3,4,5,6,7]'
>>> Foo
'[1,2,3,4,5,6,7]'
>>> Foo[0]
'['
>>> Bar = eval(Foo)
>>> Bar
[1, 2, 3, 4, 5, 6, 7]
>>> Bar[0]
1
>>>

-Hal Schechner

-=[Hal Schechner]-=-=-=-=System Administration=-=-=-=-=(hal-j@NetUSA.Net)=-
              I'm sorry, he can't come to the phone right now.              
                   His foot is caught in the ceiling fan.                   
-=[Finger for public key]-=-=-=-=-=-=-=-=-=[http://www.NetUSA.Net/~hal-j]=-


=================
DB-SIG  - SIG on Tabular Databases in Python

send messages to: db-sig@python.org
administrivia to: db-sig-request@python.org
=================