In Python, you can iterate on a string as if it were a list:
>>> for ch in string:
... print(ch)
...
9
6
h
1
1
k
In the loop above, with each iteration ch
will be a string 1-character. To find out if this character is numeric or not, you can use ch.isdigit()
. To convert it to an integer, you can use int(ch)
. So just add it all up:
soma = 0
for ch in string:
if ch.isdigit():
soma += int(ch)
print(soma)
A more concise way to do this is by using list comprehensions (or generating expressions), and the function sum()
(sum). For an example, see the response of Maniero.
It helps you?
str.isdigit()
Or do you want a more complete example? Do you already have some code started that is causing you difficulties? (in other words, tell us what you already know and what you still need to know. By the way, is this some exercise, or is it to be used in practice? I can give you one one-Liner that does this, or I can explain in more detail, with loops, etc.)– mgibsonbr
It’s just an exercise. I need to improve string manipulation. I can manipulate numbers, but I can’t really manipulate strings, so I saw this problem and I’m trying to solve it...
– Van Ribeiro
For example... the function str.isdigit() returns True or False... in case I would have to split the string and check each digit?
– Van Ribeiro
That’s right. You can do this with loops or - if you already know the concept - list understandings. I’m writing a response.
– mgibsonbr