How to extract numbers from a string in Python

In this Python tutorial, we gonna learn how to extract numbers from string.

A string is one of the main data types used in Python. It includes characters enclosed within ” “( double apostrophe) or ‘ ‘(inverted commas). It has various in-built methods to modify, delete or perform various other operations on the string.

Go to the python IDLE and type

>>> help(str)

to get the various inbuilt functions or methods.

This program emphasizes how to extract numbers from a string in python. The main aim here is achieved by splitting the string and inserting it into a list, Traversal this list and then further using the isdigit() function( Returns boolean if there is a number) to confirm if the value is a number, Printing the digit if True.

Code: extract numbers from a string in Python

def numberfromstring(string_a):
     n=list(string_a)
     for i in n:
         if i.isdigit():
             k=int(i)
             print(k)

A="h1egg2gh3"
numberfromstring(A)

Output:

1
2
3

Code Explanation:

We declared a user-defined function “numberfromstring” with parameter “string_a” to extract numbers from a given string. The parameter “string_a” stores the string on which the operation is to be performed.

  • The string is then split and typecasted to a list and stored in the memory location allocated to variable n. for eg: if the string is  “H1e2g3hh3“, the list n would be ['H','1','e','2','g','3','h','h','3']
  • Now using the for loop, we are traversing the list n and using the if condition to find the numbers in the string which are to be extracted.
  • The condition used is i.isdigit(). This condition returns True if i, on traversal turns out to be a digit. Only if the condition is true, the following statements will be executed.
  • Then i is typecasted to an integer and stored in the memory space allocated to the variable k.
  • Then k is printed when the function is called.

Another easy example:

We can do this using the in-built methods in python like isdigit(), split(). The isdigit() method does not take any parameters and returns True if all the characters in the string are digits else returns False.
Syntax:

string.isdigit()

The split() method returns a list of strings after fragmenting the given string by the specified separator.
Syntax:
string.split(separator, max)
separator-It specifies the delimiter to use while splitting the string. It is an optional argument and takes whitespace as default value.
max– It specifies the number of splits to do. It is also an optional argument and takes -1 as default value i.e. all the occurrences.
The program to extract numbers from a string using the above two methods is as follows.

#Python program to extract numbers from a string
#initializing the string
string="One postman delivered 6 letters in 15 minutes"
string_res=string.split()
result=[]
#empty list to store the resultant numbers
for i in range(len(string_res)):
#check whether the element is digit or not
     if string_res[i].isdigit():
         result.append(string_res[i])
print(result) #print the result

Output:

['6','15']

Another way to extract the numbers from the given string in Python language is to use the regex package which provides built-in methods, especially for regular expressions. We can use findall() function to check the occurrences of a number in the given string. The code using this method is as follows.

#Python Program to extract numbers from a string using regex
import re
string="One postman delivered 6 letters in 15 minutes"
temp=re.findall(r'\d+',string)
result=list(map(int,temp))
print(result)

Output:

['6','15']

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *