While programming, sometimes, we just require a certain type of data and need to discard other. This type of problem is quite common in Data Science domain, and since Data Science uses Python worldwide, its important to know how to extract specific elements. This article discusses certain ways in which only digit can be extracted. Let’s discuss the same.
Method #1 : Using join() + isdigit() + filter()
This task can be performed using the combination of above functions. The filter function filters the digits detected by the isdigit function and join function performs the task of reconstruction of join function.
# Python3 code to demonstrate # Extract digit string # using join() + isdigit() + filter() # initializing string test_string = 'g1eeks4geeks5' # printing original strings print("The original string : " + test_string) # using join() + isdigit() + filter() # Extract digit string res = ''.join(filter(lambda i: i.isdigit(), test_string)) # print result print("The digits string is : " + str(res)) |
The original string : g1eeks4geeks5 The digits string is : 145
Method #2 : Using re
The regular expressions can also be used to perform this particular task. We can define the digit type requirement, using “\D”, and only digits are extracted from the string.
# Python3 code to demonstrate # Extract digit string # using re import re # initializing string test_string = 'g1eeks4geeks5' # printing original strings print("The original string : " + test_string) # using re # Extract digit string res = re.sub("\D", "", test_string) # print result print("The digits string is : " + str(res)) |
The original string : g1eeks4geeks5 The digits string is : 145
Recommended Posts:
- Python - Extract digits from Tuple list
- Python | Extract numbers from string
- Python | Extract words from given string
- Python | Extract characters except of K string
- Python | Extract only characters from given string
- Python | Extract odd length words in String
- Python | Extract Numbers in Brackets in String
- Python | Extract Score list of String
- Python - Extract String till Numeric
- Python | Extract length of longest string in list
- Python - Extract words starting with K in String List
- Python Regex to extract maximum numeric value from a string
- Python string | digits
- Python - First K consecutive digits in String
- Python | Ways to remove numeric digits from given string
- Python | Split strings and digits from string list
- Python - Remove digits from Dictionary String Values List
- numpy.extract() in Python
- Python | Extract suffix after K
- Python | Extract URL from HTML using lxml
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

