Python | Extract numbers from string
Many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generally occurs in competitive programming and also in web development. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using List comprehension + isdigit() + split()
This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.
# Python3 code to demonstrate # getting numbers from string # using List comprehension + isdigit() +split() # initializing string test_string = "There are 2 apples for 4 persons" # printing original string print("The original string : " + test_string) # using List comprehension + isdigit() +split() # getting numbers from string res = [int(i) for i in test_string.split() if i.isdigit()] # print result print("The numbers list is : " + str(res)) |
The original string : There are 2 apples for 4 persons The numbers list is : [2, 4]
Method #2 : Using re.findall()
This particular problem can also be solved using python regex, we can use the findall function to check for the numeric occurrences using matching regex string.
# Python3 code to demonstrate # getting numbers from string # using re.findall() import re # initializing string test_string = "There are 2 apples for 4 persons" # printing original string print("The original string : " + test_string) # using re.findall() # getting numbers from string temp = re.findall(r'\d+', test_string) res = list(map(int, temp)) # print result print("The numbers list is : " + str(res)) |
The original string : There are 2 apples for 4 persons The numbers list is : [2, 4]
Recommended Posts:
- Python | Extract numbers from list of strings
- Python | Extract words from given string
- Python | Extract only characters from given string
- Python | Extract digits from given string
- Python Regex to extract maximum numeric value from a string
- numpy.extract() in Python
- Extract images from video in Python
- Python | Extract key-value of dictionary in variables
- Python | Extract URL from HTML using lxml
- Python | Pandas Series.str.extract()
- Python | Extract specific keys from dictionary
- Python | Program to extract frames using OpenCV
- Python | Extract Combination Mapping in two lists
- Python Slicing | Extract ‘k’ bits from a given position
- Python program to extract Email-id from URL text file
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.



