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"
Code language: Python (python)

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

print(sum([int(num) for num in numbers.split(" ") if num.isnumeric()])) #42
Code language: Python (python)

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.

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments