[Tutor] string to number

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 16 Apr 2002 14:57:50 -0700 (PDT)


On Tue, 16 Apr 2002, Jordan, Jay wrote:

> I have a list containing multiple strings which are numbers. [209, 30, 50,
> 123, 40, ...etc]
>
> I want to use my list but perform numerical operations on the contents
> but it wont let me use INT and the ATOL function keeps comming up as
> undefined even though I have IMPORT STRING at the top of my project. Is
> there another better way to take a string and make it a number?

Can you show us the code that you're using?  It sounds like you have a
list of strings, and if so, you can use the int() function to make them
numerical.  For example:

###
>>> mylist = ["209", "30", "50", "123"]
>>> mylist
['209', '30', '50', '123']
>>> type(mylist[0])
<type 'string'>
>>> mylist[0] + mylist[1] + mylist[2] + mylist[3]
'2093050123'
###


Here, we have a list of strings.  Even though they might look like
numbers, Python won't automatically do numeric manipulations with them
until we make them integers.  We can use the built-in int() function for
this:

###
>>> numbers = map(int, mylist)
>>> type(numbers[0])
<type 'int'>
>>> numbers
[209, 30, 50, 123]
>>> numbers[0] + numbers[1] + numbers[2] + numbers[3]
412
###


Is this what you're looking for?  If you have more questions, please feel
free to ask.  Good luck!