How to extract numbers from a string in Python?

In Python, you can use regular expressions to extract numbers from a string. The re module provides functions for working with regular expressions. Here's an example of how you can use the re module to extract all integers from a string:

import re

string = "The cost is $120 and the tax is $20.5"
numbers = [int(num) for num in re.findall(r'\d+', string)]
print(numbers)
# Output: [120, 20]

In this example, the regular expression r'\d+' is used to match one or more digits in the string. The findall() function is used to find all matches of the regular expression in the string, and the resulting matches are converted to integers using a list comprehension.

Watch a course Python - The Practical Guide

If you want to extract decimal numbers, use float() instead of int()

import re

string = "The cost is $120 and the tax is $20.5"
numbers = [float(num) for num in re.findall(r'[\d.]+', string)]
print(numbers)
# Output: [120.0, 20.5]

Note that this will also extract numbers with decimal points.