Remove zeros from list python

  1. HowTo
  2. Python How-To's
  3. Remove Leading Zeros in Python String

Created: September-15, 2021 | Updated: October-02, 2021

  1. Use Iteration Statements to Remove Leading Zeros in a String in Python
  2. Use the lstrip() Function Along With List Comprehension to Remove Leading Zeros in a String in Python
  3. Use the startswith() Method + Loop + List Slicing to Remove Leading Zeros in a String in Python

The removal of leading or trailing zeros is essential when data processing is performed, and the data has to be passed forward. A stray 0 might get attached to the string while it is transferred from one place to another, and it is recommended to remove it as it is unnecessary and inconvenient.

This tutorial demonstrates the several ways available to remove leading zeros in a string in Python.

Use Iteration Statements to Remove Leading Zeros in a String in Python

The simplest and most basic way to remove leading zeros in a string in Python is to remove them using iteration statements manually. Here, we manually create a code using a for loop along with the while loop to make a program that removes leading zeros in a string in Python.

The following code uses the for loop to remove leading zeros in a string in Python.

A = ['0001234','01000','1000',]
removeleading = []

for x in A:
  while x[0] == "0":
    x = x[1:]
  removeleading.append(x)
print(removeleading)

The above code provides the following output:

['1234', '1000', '1000']

In the above code, we use two iteration statements, a for loop and a while loop, the latter being nested within the former. Finally, we append the newly created list and then display it after making the necessary changes.

Use the lstrip() Function Along With List Comprehension to Remove Leading Zeros in a String in Python

The lstrip() can be utilized to remove the leading characters of the string if they exist. By default, a space is the leading character to remove in the string.

List comprehension is a relatively shorter and very graceful way to create lists that are to be formed based on given values of an already existing list.

We can combine these two things and use them in our favor.

The following code uses the lstrip() function along with the list comprehension to remove leading zeros in a string in Python.

A = ['0001234','01000','1000',]
res = [ele.lstrip('0') for ele in A]
print (str(res))

The above code provides the following output.

['1234', '1000', '1000']

In the above code, the lstrip() function is used to strip the leading zeros in the given string. List comprehension is used here to extend the logic further and achieve this program successfully without any errors.

Use the startswith() Method + Loop + List Slicing to Remove Leading Zeros in a String in Python

The startswith() method provides a True value when the string starts with the value that the user in the function definition specifies. We combine this startswith() function with a loop and list slicing to remove leading zeros in a string in Python.

The following code uses the startswith() method + loop + list slicing to remove leading zeros in a string in Python.

A = ['0001234','01000','1000']
for idx in range(len(A)):
    if A[idx].startswith('0'):
        A[idx] = A[idx][1:]
print (str(A))

The above code provides the following output:

['001234', '1000', '1000']

In the above code, a for loop is opened for working, and the list slicing process is done with the help of the startswith() function.

The drawback with this method is that it only removes one leading zero at a run, which can be problematic with big numbers.

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • View Discussion

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given an array of N numbers, the task is to remove all leading zeros from the array. 

    Examples: 

    Input : arr[] = {0, 0, 0, 1, 2, 3} 
    Output : 1 2 3 
    
    Input : arr[] = {0, 0, 0, 1, 0, 2, 3} 
    Output : 1 0 2 3 

    Approach: Mark the first non-zero number’s index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container. 

    Below is the implementation of the above approach: 

    C++

    #include

    using namespace std;

    void removeZeros(int a[], int n)

    {

        int ind = -1;

        for (int i = 0; i < n; i++) {

            if (a[i] != 0) {

                ind = i;

                break;

            }

        }

        if (ind == -1) {

            cout << "Array has leading zeros only";

            return;

        }

        int b[n - ind];

        for (int i = 0; i < n - ind; i++)

            b[i] = a[ind + i];

        for (int i = 0; i < n - ind; i++)

            cout << b[i] << " ";

    }

    int main()

    {

        int a[] = { 0, 0, 0, 1, 2, 0, 3 };

        int n = sizeof(a) / sizeof(a[0]);

        removeZeros(a, n);

        return 0;

    }

    Java

    import java.util.*;

    class solution

    {

    static void removeZeros(int[] a, int n)

    {

        int ind = -1;

        for (int i = 0; i < n; i++) {

            if (a[i] != 0) {

                ind = i;

                break;

            }

        }

        if (ind == -1) {

            System.out.print("Array has leading zeros only");

            return;

        }

        int[] b = new int[n - ind];

        for (int i = 0; i < n - ind; i++)

            b[i] = a[ind + i];

        for (int i = 0; i < n - ind; i++)

            System.out.print(b[i]+" ");

    }

    public static void main(String args[])

    {

        int[] a = { 0, 0, 0, 1, 2, 0, 3 };

        int n = a.length;

        removeZeros(a, n);

    }

    }

    Python3

    def removeZeros(a, n):

        ind = -1;

        for i in range(n):

            if (a[i] != 0):

                ind = i;

                break;

        if (ind == -1):

            print("Array has leading zeros only");

            return;

        b=[0]*(n - ind);

        for i in range(n - ind):

            b[i] = a[ind + i];

        for i in range(n - ind):

            print( b[i] , end=" ");

    a = [0, 0, 0, 1, 2, 0, 3];

    n = len(a);

    removeZeros(a, n);

    C#

    using System;

    class solution

    {

    static void removeZeros(int[] a, int n)

    {

        int ind = -1;

        for (int i = 0; i < n; i++)

        {

            if (a[i] != 0)

            {

                ind = i;

                break;

            }

        }

        if (ind == -1)

        {

            Console.Write("Array has leading zeros only");

            return;

        }

        int[] b = new int[n - ind];

        for (int i = 0; i < n - ind; i++)

            b[i] = a[ind + i];

        for (int i = 0; i < n - ind; i++)

            Console.Write(b[i]+" ");

    }

    public static void Main(String []args)

    {

        int[] a = { 0, 0, 0, 1, 2, 0, 3 };

        int n = a.Length;

        removeZeros(a, n);

    }

    }

    PHP

    function removeZeros($a, $n)

    {

        $ind = -1;

        for ($i = 0; $i < $n; $i++)

        {

            if ($a[$i] != 0)

            {

                $ind = $i;

                break;

            }

        }

        if ($ind == -1)

        {

            echo "Array has leading " .

                          "zeros only";

            return;

        }

        for ($i = 0; $i < $n - $ind; $i++)

            $b[$i] = $a[$ind + $i];

        for ($i = 0; $i < $n - $ind; $i++)

            echo $b[$i] , " ";

    }

    $a = array(0, 0, 0, 1, 2, 0, 3);

    $n = sizeof($a);

    removeZeros($a, $n);

    ?>

    Javascript


    How do you remove zeros from a list in Python?

    We can use the Python filter() function to extract all the items in a list of numbers which do not equal 0 and remove the zeros from a list.

    How do I remove zeros from a nested list in Python?

    Read the doc: docs.python.org/3/tutorial/datastructures.html "list. remove(x) ... Remove the first item from the list whose value is equal to x." OP, do NOT use bare except statements, this is bad practice.

    How do you remove zeros from a data set?

    Deleting Zero Values from a Data Table.
    Press Ctrl+H. ... .
    Click the Options button to expand the dialog box. ... .
    In the Find What box, enter 0..
    Make sure the Replace With box is empty..
    Select the Match Entire Cell Contents check box..
    Click Replace All to perform the replacements..

    How do you remove occurrences in Python?

    Remove all occurrences of an item from a Python list.
    Using list. remove() function. ... .
    Using List Comprehension. The recommended solution is to use list comprehension. ... .
    Using filter() function..