Skip to content
Related Articles

Related Articles

Improve Article
Python – Remove Units from Value List
  • Last Updated : 03 Jul, 2020

Sometimes, while working with Python value lists, we can have a problem in which we need to perform removal of units that come along with values. This problem can have direct application in day-day programming and data preprocessing. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [“54 cm”, “23 cm”, “12cm”, “19 cm”], unit = “cm”
Output : [’54’, ’23’, ’12’, ’19’]

Input : test_list = [“54 cm”], unit = “cm”
Output : [’54’]

Method #1 : Using regex() + list comprehension
The combination of these functions can be used to solve this problem. In this, we approach by extracting just the numbers using regex, and remove rest of string units.




# Python3 code to demonstrate working of 
# Remove Units from Value List
# Using list comprehesion + regex()
import re
  
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19  kg"
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing unit 
unit = "kg"
  
# Remove Units from Value List
# Using list comprehesion + regex()
res = re.findall('\d+', ' '.join(test_list))
  
# printing result 
print("List after unit removal : " + str(res))
Output :



The original list is : ['54 kg', '23 kg', '12kg', '19  kg']
List after unit removal : ['54', '23', '12', '19']

 

Method #2 : Using replace() + strip() + list comprehension
The combination of above functions can be used to solve this problem. In this, we perform the task of replacing unit with empty string to remove it using replace() and stray spaces are handled using strip().




# Python3 code to demonstrate working of 
# Remove Units from Value List
# Using replace() + strip() + list comprehension
import re
  
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19  kg"
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing unit 
unit = "kg"
  
# Remove Units from Value List
# Using replace() + strip() + list comprehension
res = [sub.replace(unit, "").strip() for sub in test_list]
  
# printing result 
print("List after unit removal : " + str(res))
Output :
The original list is : ['54 kg', '23 kg', '12kg', '19  kg']
List after unit removal : ['54', '23', '12', '19']

 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 :