Extract all the numbers from a string in Python

Extract numbers from string :

many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generated occurs in competitive programming and also in web development. Extract numbers from a string are using in numpy module.

Numpy:

Numpy is a general-purpose array – processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with python. Besides its obvious scientific uses,  Numpy can also be used as an efficient multi-dimensional container of generic data.

Arrays in numpy:

Arrays in Numpy is a table  of elements(usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is know as shape of the array. An array class in numpy is called as ndarray. Elements in numpy arrays are accessed by using square brackets and can be initialized by using square brackets and can be initialized by using nested python lists.

# Initialize the string
string = "Hello, my age is 29 years and 140 days"
print("Original string:",string)

# Using list comprehension and isdigit() method
numbers = [int(word) for word in string.split() if word.isdigit()]
print("After extracting numbers from a string:", numbers)

Output:


Original string: Hello, my age is 29 years and 140 days
After extracting numbers from a string: [29, 140]
 Extract all the numbers from a string in Python

Leave a Comment

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

Scroll to Top