Python | Extract digits from given string
Last Updated :
24 Mar, 2023
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
test_string = 'g1eeks4geeks5'
print ("The original string : " + test_string)
res = ''.join( filter ( lambda i: i.isdigit(), test_string))
print ("The digits string is : " + str (res))
|
Output :
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
import re
test_string = 'g1eeks4geeks5'
print ("The original string : " + test_string)
res = re.sub("\D", "", test_string)
print ("The digits string is : " + str (res))
|
Output :
The original string : g1eeks4geeks5
The digits string is : 145
Method 3: Using loops:
This task is done by using for loop.
Python3
s = "g1eeks4geeks5"
for i in s:
if (i.isdigit()):
print (i,end = "")
|
Output:
The original string : g1eeks4geeks5
The digits string is : 145
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 4: Using recursion:
Python3
def ExtractDigits(s,i = 0 ):
if i = = len (s):
return
if s[i].isdigit():
print (s[i], end = '')
i + = 1
ExtractDigits(s,i)
s = "g1eeks4geeks5"
ExtractDigits(s)
|
Method 5: Using ord() method
Python3
s = "g1eeks4geeks5"
for i in s:
if ord (i) in range ( 48 , 58 ):
print (i,end = "")
|
Method 6 : Using isnumeric() method
Approach
- Initiate a for loop to traverse the string
- Check whether the character is numeric by using isnumeric()
- Display the character if numeric
Python3
s = "g1eeks4geeks5"
for i in s:
if (i.isnumeric()):
print (i,end = "")
|
Time Complexity : O(N) N – length of string
Auxiliary Space :O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...