- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract decimal numbers from a string in Python \n\n
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.
Where,
\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.
Example
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.
Output
On executing the above code snippet, the below output is obtained.
['40.5']