Thursday, September 21, 2023
HomeSoftware EngineeringCalculate the Sum of all Numbers in a String in Python

Calculate the Sum of all Numbers in a String in Python


Let’s take the next string:

numbers = "this 1 2 3 4 5 shouldn't be a 8 9 10"

How can we sum up all of the numbers on this string?

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

Within the above code snippet, we break up the string by the area character, then loop by it and ignore something that isn’t numeric. Then we sum up the numbers which can be remaining.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments