Python Practice › String Programs › Program 16

Extract all numbers from a string

EasyString Programs · 16 of 106

Write a Python program to get all the numbers from a multi-line string.

Advertisement
Input
a paragraph containing 1112, 1773, 444, 5324 and 555
Output
[1112, 1773, 444, 5324, 555]

Approach

  1. Use re.findall(r"\d+", text) and convert each match to int.

Solution

Python
import re text = """Sinak's 1112 aim is to 1773 create a new generation of people whounderstand 444 that an organization's 5324 success or failure isbased on 555 leadership excellence and not managerial acumen"""numbers = [int(n) for n in re.findall(r"\d+", text)]print(numbers)
Output
[1112, 1773, 444, 5324, 555]

Line by line

Line 6

\d+ matches each run of digits; the list comprehension converts them to integers.

Note

The original sample output listed 5324 twice and missed 444; the real numbers in the text are shown here.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Leave a Comment