Hello, readers! In this article, we will be focusing on the ways to extract digits from a Python String. So, let us get started.
1. Making use of isdigit() function to extract digits from a Python string
Python provides us with
string.isdigit() to check for the presence of digits in a string.
Python isdigit() function returns True if the input string contains digit characters in it.
We need not pass any parameter to it. As an output, it returns True or False depending upon the presence of digit characters in a string.
inp_str = "Python4Journaldev" print("Original String : " + inp_str) num = "" for c in inp_str: if c.isdigit(): num = num + c print("Extracted numbers from the list : " + num)
In this example, we have iterated the input string character by character using a for loop. As soon as the isdigit() function encounters a digit, it will store it into a string variable named ‘num’.
Thus, we see the output as shown below–
Original String : Python4Journaldev Extracted numbers from the list : 4
Now, we can even use Python list comprehension to club the iteration and idigit() function into a single line.
By this, the digit characters get stored into a list ‘num’ as shown below:
inp_str = "Hey readers, we all are here be 4 the time!" print("Original string : " + inp_str) num = [int(x) for x in inp_str.split() if x.isdigit()] print("The numbers list is : " + str(num))
Original string : Hey readers, we all are here be 4 the time! The numbers list is : 
2. Using regex library to extract digits
Python regular expressions library called ‘regex library‘ enables us to detect the presence of particular characters such as digits, some special characters, etc. from a string.
We need to import the regex library into the python environment before executing any further steps.
Further, we we
re.findall(r'\d+', string) to extract digit characters from the string. The portion ‘\d+’ would help the findall() function to detect the presence of any digit.
import re inp_str = "Hey readers, we all are here be 4 the time 1!" print("Original string : " + inp_str) num = re.findall(r'\d+', inp_str) print(num)
So, as seen below, we would get a list of all the digit characters from the string.
Original string : Hey readers, we all are here be 4 the time 1! ['4', '1']
By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.
I recommend you all to try implementing the above examples using data structures such as lists, dict, etc.
For more such posts related to Python, Stay tuned and till then, Happy Learning!! 🙂