Converting String to int

Tim Chase python.list at tim.thechases.com
Sun May 14 20:33:52 EDT 2006


> Hi all, Another problem, with the same error (error: "invalid literal for 
> int()")

Having the actual code would be helpful...

> code:
> 
> mynums = "423.523.674.324.342.122.943.421.762.158.830"
> 
> mynumArray = string.split(mynums,".")
> 
> x = 0
> for nums in mynumArray:
>    if nums.isalnum() == true:

This line would likely bomb, as in python, it's "True", not 
"true" (unless you've defined lowercase versions elsewhere)

> 	x = x + int(nums)
>    else:
> 	print "Error, element contains some non-numeric characters"
> 	break

However, I modified your code just a spot, and it worked 
like a charm:

mynums = "423.523.674.324.342.122.943.421.762.158.830"
mynumArray = mynums.split(".")
x = 0
for num in mynumArray:
     if num.isdigit():
         x = x + int(num)
     else:
         print "Error"
         break

and it worked fine.

A more pythonic way may might be

x = sum([int(q) for q in mynumArray if q.isdigit()])

or, if you don't need mynumArray for anything, you can just use

x = sum([int(q) for q in mynum.split(".") if q.isdigit()])

Hope this gives you some stuff to work with,

-tkc












More information about the Python-list mailing list