Re: Converting String to int
> 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting String to int
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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting String to int
Hi all, Another problem, with the same error (error: "invalid literal for int()") 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: x = x + int(nums) else: print "Error, element contains some non-numeric characters" break /end code This seemed like a simple thing, and I have done it before with no issues. have I missed something obvious? taking into account my previous hex question, I tried changing int(nums) to int(nums,10) but it still gives me the error -- http://mail.python.org/mailman/listinfo/python-list