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

0 min read 72 words

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.

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags