
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find All Numbers in a String Using Regular Expression in Python
Extracting only the numbers from a text is a very common requirement in python data analytics. It is done easily using the python regular expression library. This library helps us define the patterns for digits which can be extracted as substrings.
Examples
In the below example we use the function findall() from the re module. The parameters to these function are the pattern which we want to extract and the string from which we want to extract. Please note with below example we get only the digits and not the decimal points or the negative signs.
import re str=input("Enter a String with numbers: \n") #Create a list to hold the numbers num_list = re.findall(r'\d+', str) print(num_list)
Output
Running the above code gives us the following result −
Enter a String with numbers: Go to 13.8 miles and then -4.112 miles. ['13', '8', '4', '112']
Capturing the Decimal point and Signs
We can expand the search pattern to include the decimal points and the negative or positive signs also in the search result.
Examples
import re str=input("Enter a String with numbers: \n") #Create a list to hold the numbers num_list=re.findall(r'[-+]?[.]?[\d]+',str) print(num_list)
Output
Running the above code gives us the following result −
Enter a String with numbers: Go to 13.8 miles and then -4.112 miles. ['13', '.8', '-4', '.112']