Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Extract integers from a string

Find all integer numbers embedded in a text and return them as a list of ints in order of appearance.

Python practice15 minString PatternsIntermediateLast updated March 18, 2026

Problem statement

Given an input string that may contain letters, punctuation, signs and digits, extract every contiguous integer found in the string and return them as a list of Python ints in the order they appear. A valid integer is a sequence of digits optionally preceded by a single '-' minus sign. Leading zeros should be properly converted by Python's int conversion. If no integers are present, return an empty list.

Task

Learn to scan strings for numeric patterns (including negative numbers) and convert matched substrings into integers.

Examples

Basic example with negative and positive numbers

Input

Order #123 - item -45 and +7? (note: + sign not considered)

Output

[-123? No, see below]

This example clarifies that only patterns like '-45' and '123' are considered; explicit '+' is not handled as part of an integer for this task. (In practice, for the input 'a-12b34' you should return [-12, 34].)

Input format

A single string passed to extract_ints(s).

Output format

A Python list of integers (e.g. [1, -2, 3]).

Constraints

Only a leading '-' is allowed for negative numbers. '+' is not treated as part of a number. Numbers are contiguous digit sequences (0-9). The function should handle empty strings and return an empty list when no integers are found.

Samples

Sample 1

Input

foo -12 bar 34

Output

[-12, 34]

Two integers are present: -12 and 34, returned as ints in a list in appearance order.