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)
-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Python,
- Python: Convert Date to DateTime
- How to sort a List using Lambda in Python
- Python matplotlib segmentation fault: 11 macOS Big Sur
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to install Python 3.11 on Mac
- How to flatten a nested list in Python
- Python: Pandas Merge DataFrames on Index Example
- How to Run all Cells at Once Jupyter Notebook
- Python - Convert float to String
- How to add borders to tkinter label text
- How to Exit a Loop in Python Code
- [Python] Fix: ValueError: All arrays must be of the same length
- Sorting an array using Bubble Sort in Python Programming
- How to Unzip a file using Python
- Python: Merge DataFrames Pandas Outer Join Example
- Change label (text) color in tkinter
- Convert Float to String in Python
- Fix: fatal error: No such file or directory compilation terminated
- Python: Access index/counter of a for loop iteration
- Import Other Python Files Examples
- How to install Anaconda on Mac (M1/M2 Mac)
- Python Regular Expression to Find All Matches in List
- How to Read a binary File with Python
- How to disable warnings while Python file execution
- Know current Python Version
More Posts:
- Path of homebrew (brew) installation in macOS Big Sur - MacOS
- Replace delimiter with new line in Notepad++ - NotepadPlusPlus
- How to destroy PHP session() - PHP
- Comparator with Lambda Examples - Java
- Fix RabbitMQ: AuthenticationFailureException: ACCESS_REFUSED - Java
- Notepad++ sort by name with example - NotepadPlusPlus
- Create Safari Shortcut on Mac Desktop - MacOS
- Java code to check Internet Connection on Android Device Programmatically - Android