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 on how to extract numbers from a string in python. The main aim here is achieved by splitting the string and inserting into a list, Traversal of 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):
     for i in n:
         if i.isdigit():




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.

Also read:

Leave a Reply

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