How to Calculate the Sum of All Numbers in a String in Python


Let’s take the following string:

numbers = "this 1 2 3 4 5 is not a 8 9 10"

How can we sum up all the numbers in this string?

print(sum([int(num) for num in numbers.split(" ") if num.isnumeric()]))
#42

In the above code snippet, we split the string by the space character, then loop through it and ignore anything that is not numeric. Then we sum up the numbers that are remaining.