Skip to content
Related Articles

Related Articles

Improve Article

Python – Retain Numbers in String

  • Last Updated : 03 Jul, 2020

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.




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




# 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)) 
Output :
The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :