- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 nn
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']
- Related Articles
- Extract decimal numbers from a string in Python \n\n
- How to extract numbers from a string in Python?
- How to extract numbers from a string using Python?
- How to extract the first n characters from a string using Java?
- How to extract the last n characters from a string using Java?
- Python – Extract Percentages from String
- Program to find duplicate element from n+1 numbers ranging from 1 to n in Python
- Python program to print decimal octal hex and binary of first n numbers
- How to extract date from a string in Python?
- Python program for removing n-th character from a string?
- How to extract numbers from a string using regular expressions?
- String Operations in Python\n
- Extract numbers from list of strings in Python
- Python – Extract Rear K digits from Numbers
- Extract only characters from given string in Python
- How to extract a substring from inside a string in Python?
