Python – Retain Numbers in String

Sometimes, while working with Python Strings, we can have a problem in which we need to perform the removal of all the characters other than integers. This kind of problem can have application in many data domains such as Machine Learning and web development. Let’s discuss certain ways in which this task can be performed.

Input : test_str = ‘G4g is No. 1’
Output : 41

Input : test_str = ‘Gfg is No. 1’
Output : 1

Method #1 : Using list comprehension + join() + isdigit()
The combination of above functions can be used to solve this problem. In this, we perform the task of extracting integers using isdigit(), list comprehension is used for iteration and join() is used to perform join of numbers filtered.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Retain Numbers in String
# Using list comprehension + join() + isdigit()
  
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
  
# printing original string
print("The original string is : " + str(test_str))
  
# Retain Numbers in String
# Using list comprehension + join() + isdigit()
res = "".join([ele for ele in test_str if ele.isdigit()])
  
# printing result 
print("String after integer retention : " + str(res)) 

chevron_right


Output :



The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

 

Method #2 : Using regex()
The solution of problem can also be found by using regex. In this, we formulate appropriate regex to filter only numbers from string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Retain Numbers in String
# Using regex()
import re
  
# initializing string
test_str = 'G4g is No. 1 for Geeks 7'
  
# printing original string
print("The original string is : " + str(test_str))
  
# Retain Numbers in String
# Using regex()
res = re.sub(r'[^\d]+', '', test_str) 
  
# printing result 
print("String after integer retention : " + str(res)) 

chevron_right


Output :

The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.