- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Python â€“ How to Extract all the digits from a String
When it is required to extract strings with a digit, a list comprehension and ‘isdigit’ method is used.
Below is a demonstration of the same −
my_string = "python is 12 fun 2 learn" print("The string is : ") print(my_string) my_result = [int(i) for i in my_string.split() if i.isdigit()] print("The numbers list is :") print(my_result)
The string is : python is 12 fun 2 learn The numbers list is : [12, 2]
A string is defined and is displayed on the console.
A list comprehension is used to iterate over the string, and every element is checked to see if it is a digit using the ‘isdigit’ function and is converted to an integer.
These are stored in a list and assigned to a variable.
This is the output that is displayed on the console.
- Related Articles
- Extract digits from Tuple list Python
- How to extract numbers from a string in Python?
- How to extract date from a string in Python?
- How to extract numbers from a string using Python?
- Python â€“ Extract Rear K digits from Numbers
- How to extract a substring from inside a string in Python?
- How to extract data from a string with Python Regular Expressions?
- Python â€“ Extract Percentages from String
- How to extract all the .txt files from a zip file using Python?
- Get all digits from a string in Java
- Extract all integers from string in C++
- How to extract all string values from a vector in R with maximum lengths?
- Python Regex to extract maximum numeric value from a string
- How to remove characters except digits from string in Python?
- Python program to extract only the numbers from a list which have some specific digits