Move your try
within the loop, and ignore the exception by using pass
as the exception handler:
digitsum = 0
for i in s:
try:
digitsum += int(i)
except ValueError:
pass # ignore non-digit characters
You won't hit a TypeError
here unless any i
is a type of object that int()
cannot handle; e.g. anything not a number or a string:
>>> int({})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'dict'