Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Remove suffix from string list
Next article icon

Python – Remove leading 0 from Strings List

Last Updated : 04 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python, we can have a problem in which we have data which we need to perform processing and then pass the data forward. One way to process is to remove a stray 0 that may get attached to a string while data transfer. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using lstrip() + list comprehension 

This is one of the one-liners with the help of which this task can be performed. In this, we strip the leading 0 using lstrip and the extension of logic to list is done using list comprehension. 

Step-by-step approach:

  • Initialize a list of strings.
  • Print the original list of strings.
  • Use a list comprehension to loop through each element in the list.
  • For each element, use the lstrip() method to remove any leading 0s.
  • Append the modified string to a new list.
  • Print the new list of strings with leading 0s removed.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# Remove leading 0 from Strings List
# using lstrip() + list comprehension
 
# Initializing list
test_list = ['012', '03', '044', '09']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove leading 0 from Strings List
# using lstrip() + list comprehension
res = [ele.lstrip('0') for ele in test_list]
 
# printing result
print("The string list after leading 0 removal : " + str(res))
 
 
Output
The original list is : ['012', '03', '044', '09'] The string list after leading 0 removal : ['12', '3', '44', '9']

Time Complexity: O(N)
Auxiliary Space: O(1)

Method #2: Using startswith() + loop + list slicing 

This is one of the ways in which this task can be performed. In this, we check for the initial 0 using startswith(), and then list slicing is used to remake the string excluding 0. 

Python3




# Python3 code to demonstrate
# Remove leading 0 from Strings List
# using startswith() + loop + list slicing
 
# Initializing list
test_list = ['012', '03', '044', '09']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove leading 0 from Strings List
# using startswith() + loop + list slicing
for idx in range(len(test_list)):
    if test_list[idx].startswith('0'):
        test_list[idx] = test_list[idx][1:]
 
# printing result
print("The string list after leading 0 removal : " + str(test_list))
 
 
Output
The original list is : ['012', '03', '044', '09'] The string list after leading 0 removal : ['12', '3', '44', '9']

Time Complexity: O(N)
Auxiliary Space: O(1)

Method #3 : Using find() and slicing methods

Python3




# Python3 code to demonstrate
# Remove leading 0 from Strings List
 
# Initializing list
test_list = ['012', '03', '044', '09']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove leading 0 from Strings List
 
for i in range(len(test_list)):
    if test_list[i].find('0') == 0:
        test_list[i] = test_list[i][1:]
 
# printing result
print("The string list after leading 0 removal : " + str(test_list))
 
 
Output
The original list is : ['012', '03', '044', '09'] The string list after leading 0 removal : ['12', '3', '44', '9']

Time Complexity: O(N)
Auxiliary Space: O(1)

Method #4 : Using int() function

Python3




# Python3 code to demonstrate
# Remove leading 0 from Strings List
 
# Initializing list
test_list = ['012', '03', '044', '09']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove leading 0 from Strings List
 
for i in range(len(test_list)):
    test_list[i] = int(test_list[i])
 
# printing result
print("The string list after leading 0 removal : " + str(test_list))
 
 
Output
The original list is : ['012', '03', '044', '09'] The string list after leading 0 removal : [12, 3, 44, 9]

Time Complexity: O(N)
Auxiliary Space: O(1)

Method #5: Using regex Expressions

One more approach to solving this problem could be using Regular Expressions (re module). We can use the re.sub() function to search for the pattern ‘^0+’ (i.e., one or more zeros at the start of the string) and replace it with an empty string.

Python3




# Python3 code to demonstrate
# Remove leading 0 from Strings List
# using re.sub()
 
import re
 
# Initializing list
test_list = ['012', '03', '044', '09']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove leading 0 from Strings List
# using re.sub()
 
res = [re.sub("^0+", "", ele) for ele in test_list]
 
# printing result
print("The string list after leading 0 removal : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original list is : ['012', '03', '044', '09'] The string list after leading 0 removal : ['12', '3', '44', '9']

Time Complexity: O(N)
Auxiliary Space: O(1)

Method #6: Using map() function

You can use the map() function to apply the int() function to each element of the list in a more concise way than using a for loop. Here’s how to use map() to remove leading zeros from strings in a list:

  1. Initialize a list test_list with elements as strings containing leading zeros.
  2. Print the original list using print() function.
  3. Use the map() function to apply the int() function to each element of the list in a concise way using a lambda function.
  4. Convert the output of map() function to list using list() function and store it in test_list.
  5. Print the final list with leading zeros removed using print() function.

Python3




# Initializing list
test_list = ['012', '03', '044', '09']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove leading 0 from Strings List using map() function
test_list = list(map(lambda x: int(x), test_list))
 
# printing result
print("The string list after leading 0 removal : " + str(test_list))
 
 
Output
The original list is : ['012', '03', '044', '09'] The string list after leading 0 removal : [12, 3, 44, 9]

Time complexity: O(n) where n is the number of elements in the list.
Auxiliary space: O(n) because we create a new list with the same number of elements as the original list.



Next Article
Python - Remove suffix from string list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Remove given character from Strings list
    Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let's discuss certain ways to solve this problem. Method #1 : Using replace() + enumerate() + loop This is
    8 min read
  • Python - Remove suffix from string list
    To remove a suffix from a list of strings, we identify and exclude elements that end with the specified suffix. This involves checking each string in the list and ensuring it doesn't have the unwanted suffix at the end, resulting in a list with only the desired elements. Using list comprehensionUsin
    3 min read
  • Python | Remove prefix strings from list
    Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings starting with a specific prefix are removed. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + remove() + startswith() The combinati
    5 min read
  • Python | Remove Kth character from strings list
    Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be perfor
    7 min read
  • Python - Remove substring list from String
    In Python Strings we encounter problems where we need to remove a substring from a string. However, in some cases, we need to handle a list of substrings to be removed, ensuring the string is adjusted accordingly. Using String Replace in a LoopThis method iterates through the list of substrings and
    3 min read
  • Python | Remove trailing/leading special characters from strings list
    Sometimes, while working with String lists, we can have a problem in which we need to perform the deletion of extra characters that can be termed as unwanted and occur at end of each string. Let's discuss a way in which this task can be performed. Method 1: Using map() + str.strip() A combination of
    5 min read
  • Remove spaces from a string in Python
    Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so: Using replace() methodTo remove all spaces from a
    2 min read
  • Python | Remove all digits from a list of strings
    The problem is about removing all numeric digits from each string in a given list of strings. We are provided with a list where each element is a string and the task is to remove any digits (0-9) from each string, leaving only the non-digit characters. In this article, we'll explore multiple methods
    4 min read
  • Python - Remove Rear K characters from String List
    Sometimes, we come across an issue in which we require to delete the last characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plu
    5 min read
  • Python | Remove trailing empty elements from given list
    When working with lists in Python, it's common to encounter lists with extra None elements at the end. These trailing None values can cause issues in our programs . We can remove these trailing None elements using simple methods like slicing, loops, or filter. Using List Slicing Slicing is a very ef
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences