Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Extract numbers from string

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 07 Feb, 2023
Improve Article
Save Article

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




# 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))

Output : 

The original string : There are 2 apples for 4 persons
The numbers list is : [2, 4]

Time Complexity: O(n), where n is the number of elements in the input string.
Auxiliary Space: O(n), where n is the number of numbers in the input string.

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




# 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))

Output : 

The original string : There are 2 apples for 4 persons
The numbers list is : [2, 4]

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!