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]

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)
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!