Python Program to Extract Numbers from a String
Beginner · Strings
This program pulls the numbers out of a sentence, so "3 notebooks for 120 rupees" gives the numbers 3 and 120. It reads the string one character at a time and joins neighbouring digits into whole numbers.
Program
String: I bought 3 notebooks for 120 rupees and 12 pens for 60 rupees Numbers found: [3, 120, 12, 60] Sum of the numbers: 195
How it works
currentcollects the digits of the number being read, so 1, 2 and 0 build up to "120".- When a character that is not a digit arrives, the number has ended, so
currentis turned into anintand added to the list. - A number at the very end of the string has nothing after it, which is why there is one more check after the loop.
- This version finds whole numbers only; the first alternative also handles decimals and minus signs.
Other ways to write it
Using re.findall()
Digit groups: ['4', '5', '2', '3'] Numbers with signs and decimals: [4.5, -2.0, 3.0]
\d+ means one or more digits, so it splits 4.5 into 4 and 5 and loses the minus sign. Adding an optional sign -? and an optional decimal part (?:\.\d+)? reads 4.5 and -2 correctly.
Using split() and isdigit()
Marks found: [87, 92, 78] Total: 257 | Average: 85.67
This works when numbers stand as separate words, and strip(",.") removes a comma or full stop stuck to the end. A number joined to letters, like "120rs", would be missed.
Try it yourself
End the sentence with a number, like "...and 12 pens for 60", and check that the last number is still found.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Check if a String Is a Number
- Count Letters, Digits and Spaces in a String
- Find the Sum of Elements in a List
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Count the Words in a String
All Python programs · CBSE class 12 practical file · Python exercises