Converting String to int

Heiko Wundram me+python at modelnine.org
Sun May 14 16:33:37 EDT 2006


Am Sonntag 14 Mai 2006 22:23 schrieb Ognjen Bezanov:
> mynums = "423.523.674.324.342.122.943.421.762.158.830"
>
> mynumArray = string.split(mynums,".")

This is the old way of using string functions using the module string. You 
should only write this as:

mynumArray = mynums.split(".")

(using the string methods of string objects directly)

> x = 0
> for nums in mynumArray:

This is misleading. Rename the variable to num, as it only contains a single 
number.

>    if nums.isalnum() == true:

.isalnum() checks whether the string consists of _alpha_-numeric characters 
only. So, in this case, it may contain letters, among digits. .isdigit() 
checks whether it is a (base <= 10) number.

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

As you don't know what the offending element is, insert a:

        print nums

here.

> 	break

If you change the code as noted above, it works fine for me.

--- Heiko.



More information about the Python-list mailing list