Editor

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

extract_numbers.py
text = "I bought 3 notebooks for 120 rupees and 12 pens for 60 rupees" # or: text = input("Enter a string: ")
numbers = []
current = ""
for ch in text:
if ch.isdigit():
current += ch # build the number digit by digit
elif current != "":
numbers.append(int(current))
current = ""
if current != "":
numbers.append(int(current)) # a number at the very end
print("String:", text)
print("Numbers found:", numbers)
print("Sum of the numbers:", sum(numbers))
Output
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

  1. current collects the digits of the number being read, so 1, 2 and 0 build up to "120".
  2. When a character that is not a digit arrives, the number has ended, so current is turned into an int and added to the list.
  3. A number at the very end of the string has nothing after it, which is why there is one more check after the loop.
  4. This version finds whole numbers only; the first alternative also handles decimals and minus signs.

Other ways to write it

Using re.findall()

Using re.findall()
import re
text = "The temperature fell from 4.5 to -2 degrees in 3 hours"
digit_groups = re.findall(r"\d+", text)
numbers = re.findall(r"-?\d+(?:\.\d+)?", text)
print("Digit groups:", digit_groups)
print("Numbers with signs and decimals:", [float(n) for n in numbers])
Output
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()

Using split() and isdigit()
text = "Rahul scored 87 in maths, 92 in science and 78 in English."
numbers = []
for word in text.split():
word = word.strip(",.")
if word.isdigit():
numbers.append(int(word))
print("Marks found:", numbers)
print("Total:", sum(numbers), "| Average:", round(sum(numbers) / len(numbers), 2))
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises