Extract decimal numbers from a string in Python

To extract decimal numbers from a string in Python, regular expressions are used.

A regular expression is a group of characters that allows you to use a search pattern to find a string or a set of strings. RegEx is another name for regular expressions.

The re module in Python is used to work with regular expressions.

In this article, we will get to know how to extract decimal numbers from a string in python using regular expressions.

We use \d+\.\d+ regular expression in python to get non digit characters from a string.


  • \d returns a match where the string contains digits (numbers from 0 9)

  • + implies zero or more occurrences of characters.

  • \ signals a special sequence (can also be used to escape special characters).

  • . is any character (except newline character).

Using findall() function

In the following example, let us assume ‘Today's temperature is 40.5 degrees.’ as a string. Here, we need to extract decimal number 40.5 from the string.


The following is an example code through which the decimals are extracted from a string in python. We begin by importing regular expression module.

import re

Then, we have used findall() function which is imported from the re module.

import re string = "Today's temperature is 40.5 degrees." x=re.findall("\d+\.\d+",string) print(x)

The re.findall() function returns a list containing all matches, that is list of strings with non-digits.


On executing the above code snippet, the below output is obtained.


Updated on: 03-Nov-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started