How to find the sum of the numbers in the given string in Python
In this tutorial, We will see How to find the sum of the numbers in the given string in Python. This tutorial is based on the Regular expression or regex module i.e re module. So, to solve this problem we have to understand the regular expression module.
What is the regular expression module in Python?
Python has an inbuilt re module which allows us to solve the various problem based on pattern matching and string manipulation.
Find all integer values in the given string by regular expression in Python
Before going to find the sum of the numbers in the given string, We have to learn how to find all numbers in the given string by using re module. So, let’s start to understand
import re string="My17name22is8bipin" number=re.findall('\d+',string) print(number)
['17', '22', '8']
Here, We include re module by using the import function and assume the input provided from the user is My17name22is8bipin. By using the findall function from the re module we separated the number as a list. In the regular expression, ‘\d+’ used to find all integer value in the given input from the user.
Find the sum of numbers in the given string in Python
As we have seen that the number is in list form that why for summation of all integer we have to run a for loop in the program. Now we are going to write the Python code.
import re string="My17name22is8bipin" number=re.findall('\d+',string) sum=0 for j in number: sum+=int(j) print(sum)
So, Guy’s I hope you enjoy this tutorial and feel free to leave a comment if you have any doubt.
You may also read: