How to extract numbers as list from Python String


If you have a string and you want to extract numbers from it as a list of integers, you can make use of the re module (regular expressions)

Let us take a look at some examples.


Example 1:

Firstly we need to import the re module.

import re

Let's say we have a string with marks for each subject.

marks_string = "Math: 95, Science: 88, English: 92, History: 87"

We can make use of re.findall() method to extract all numbers (d+) as a list of numbers as strings.

marks_list = re.findall(r'\d+', marks_string)

If you want the numbers to be a list of int then you can do that by the below step.

marks_list_int = [int(mark) for mark in marks_list]

Let's take a look at the complete code in action.

Complete code:
import re

marks_string = "Math: 95, Science: 88, English: 92, History: 87"

marks_list = re.findall(r'\d+', marks_string)

marks_list_int = [int(mark) for mark in marks_list]

print(marks_list)
Output:
[95, 88, 92, 87]
extract numbers as list from Python String example


Let's take a look at another example.

Example 2: Extract List of Decimal Numbers from a String.
import re

text = "Carrots: $1.99, Tomatoes: $2.50, Cabbage: $0.99, Bell Pepper: $1.25"

decimal_list = re.findall(r'\d+\.\d+', text)

decimal_list = [float(decimal) for decimal in decimal_list]

print(decimal_list)

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap