How to Extract All the Numbers Contained in a String in Python


Using List Comprehension

List comprehensions provide a concise way to create lists.

If you only want to extract only positive integers, try the following:


s = "The 2.0L 2023 AMG C 63 Wagon"

l = [int(c) for c in s.split() if c.isdigit()]
[2023, 63]

The other solution is:


s = "The2.0L2023AMGC63Wagon"

s = ''.join((ch if ch in '0123456789.' else ' ') for ch in s)
l = [float(i) for i in s.split()]
[2.0, 2023.0, 63.0]

Using Regexp

A more robust version would be:


# Import module
import re

s = "The2.0L2023AM.GC63Wagon"

l = re.findall(r'[-+]?(?:\d*\.\d+|\d+)', s)
[2023, 63]

To catch different patterns it is helpful to query with different patterns.

different number patterns
(finds commas) 12,300 or 12,300.00
(finds floats) 0.123 or .123
(finds integers) 123
(finds integers) 123
Combine with pipe ( | ) into one pattern with multiple or conditionals.

Related Tags