The Wayback Machine - https://web.archive.org/web/20240825193045/https://www.geeksforgeeks.org/python-program-for-remove-leading-zeros-from-a-number-given-as-a-string/
Open In App

Python Program for Remove leading zeros from a Number given as a string

Last Updated : 18 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Medium
48.03%
11.3K

Given numeric string str, the task is to remove all the leading zeros from a given string. If the string contains only zeros, then print a single “0”.

Examples:

Input: str = “0001234” 
Output: 1234 
Explanation: 
Removal of leading substring “000” modifies the string to “1234”. 
Hence, the final answer is “1234”.

Input: str = “00000000” 
Output: 0 
Explanation: 
There are no numbers except 0

Remove leading zeros from a Number given

The simplest approach to solve the problem is to traverse the string up to the first non-zero character present in the string and store the remaining string starting from that index as the answer. If the entire string is traversed, it means all the characters in the string are ‘0’. For this case, store “0” as the answer. Print the final answer. 

Below is the implementation of the above idea:

Python3




# Python Program to remove all the leading
# zeros from a given numeric string
  
# Function to remove the leading zeros
def removeLeadingZeros(num):
  
    # traverse the entire string
    for i in range(len(num)):
  
        # check for the first non-zero character
        if num[i] != '0':
            # return the remaining string
            res = num[i::];
            return res;
          
    # If the entire string is traversed
    # that means it didn't have a single
    # non-zero character, hence return "0"
    return "0";
  
# Driver Code
num = "1023";
print(removeLeadingZeros(num));
  
num = "00123";
print(removeLeadingZeros(num));


Output

1023
123

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

Remove leading zeros from a Number given Using Space-Efficient Approach

Follow the steps below to solve the problem in constant space using Regular Expression: 

  • Create a Regular Expression as given below to remove the leading zeros

regex = “^0+(?!$)” 
where: 
^0+ match one or more zeros from the beginning of the string. 
(?!$) is a negative look-ahead expression, where “$” means the end of the string. 

  • Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String.
  • To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter.
  • This method replaces the matched value with the given string.

Below is the implementation of the above approach:

Python3




# Python3 Program to implement 
# the above approach 
import re
  
# Function to remove all leading 
# zeros from a given string
def removeLeadingZeros(str):
  
    # Regex to remove leading 
    # zeros from a string 
    regex = "^0+(?!$)"
  
    # Replaces the matched 
    # value with given string 
    str = re.sub(regex, "", str)
  
    print(str)
  
# Driver Code 
str = "0001234"
removeLeadingZeros(str)


Output

1234

Time Complexity: O(N), where N is the length of the string. 
Auxiliary Space: O(1)

Remove leading zeros from a Number given Using Built in methods

use the built-in string method lstrip to remove leading zeros. This method removes all leading characters that match a specified set of characters from a string. To remove leading zeros, we can pass ‘0’ as the set of characters to remove.

Here is an example of how to use lstrip to remove leading zeros from a string:

Python3




def remove_leading_zeros(num):
    return num.lstrip('0')
  
print(remove_leading_zeros('0001234')) # Output: '1234'
print(remove_leading_zeros('00000000')) # Output: ''


Output

1234

 Time complexity:  O(N) 
 Auxiliary space: O(1), where N is the length of the string.
 

Please refer complete article on Remove leading zeros from a Number given as a string for more details!



Similar Reads

Remove leading zeros from a Number given as a string
Given numeric string str, the task is to remove all the leading zeros from a given string. If the string contains only zeros, then print a single "0". Examples: Input: str = "0001234" Output: 1234 Explanation: Removal of leading substring "000" modifies the string to "1234". Hence, the final answer is "1234". Input: str = "00000000" Output: 0 Expla
7 min read
Python | C++ | Remove leading zeros from an IP address
Given an IP address, remove leading zeros from the IP address. Examples: Input : 100.020.003.400 Output : 100.20.3.400 Input :001.200.001.004 Output : 1.200.1.4Recommended PracticeRemove leading zeros from an IP addressTry It! The approach is to split the given string by “.” and then convert it to an integer which removes the leading zeros and then
4 min read
Number of leading zeros in binary representation of a given number
Given a positive integer N, the task is to find the number of leading zeros in its binary representation.A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form. Examples: Input : N = 16Output : 27Explanation: As Binary(16) = (00000000000000000000000000010000) Input : N = 33Output : 26Explanation: As Binary
10 min read
Remove leading zeros from an array
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 arra
7 min read
Python | Add leading Zeros to string
Here, we will learn how to pad or add leading zeroes to the output as per the requirements. Let's discuss certain ways in which this problem can be solved in Python. Example: Input: GFG Output: 0000GFG Explanation: Added four zeros before GFG.Display a String With Leading Zeros in PythonAdd leading Zeros to the string using rjust() This function of
6 min read
Python | pandas int to string with leading zeros
In Python, When it comes to data manipulation and data analysis, Panda is a powerful library that provides capabilities to easily encounter scenarios where the conversion of integer to string with leading zeros is needed. In this article, we will discuss How we can convert pandas int to string with leading zeros using Python? with the help of vario
4 min read
How to Add leading Zeros to a Number in Python
In this article, we will learn how to pad or add leading zeroes to the output in Python. Example:Input: 11 Output: 000011 Explanation: Added four zeros before 11(eleven).Display a Number With Leading Zeros in PythonAdd leading Zeros to numbers using format() For more effective handling of sophisticated string formatting, Python has included the for
3 min read
Check if any permutation of a number without any leading zeros is a power of 2 or not
Given an integer N, the task is to check if any permutation of N without any leading zeros is a power of 2. If any such permutation of the given number exists, then print that permutation. Otherwise, print No. Examples: Input: N = 46Output: 64Explanation:The permutation of 46 which is perfect power of 2 is 64( = 26) Input: N = 75Output: NoExplanati
9 min read
All possible numbers of N digits and base B without leading zeros
Given a number of digits 'N' and base 'B', the task is to count all the 'N' digit numbers without leading zeros that are in base 'B' Examples: Input: N = 2, B = 2 Output: 2 All possible numbers without leading zeros are 10 and 11. Input: N = 5, B = 8 Output: 28672 Approach: If the base is 'B' then every digit of the number can take any value within
4 min read
Count numbers having N 0's and M 1's with no leading zeros
Given two integer N and M, the task is to find the number of distinct numbers having N 0's and M 1's with no leading zeros and N + M total digits. Examples: Input: N = 2, M = 2 Output: 3 The numbers are 1001, 1010 and 1100. Input: N = 2, M = 3 Output: 6 The numbers are 10011, 10101, 10110, 11001, 11010 and 11100. Approach: The problem can be easily
5 min read
Count of N-bit binary numbers without leading zeros
Given an integer N, the task is to find the count of N-bit binary numbers without leading zeros.Examples: Input: N = 2 Output: 2 10 and 11 are the only possible binary numbers.Input: N = 4 Output: 8 Approach: Since the numbers cannot have leading zeros so the left-most bit has to be set to 1. Now for the rest of the N - 1 bits, there are two choice
2 min read
Comparing leading zeros in binary representations of two numbers
Given two integer numbers x and y. Compare and print which one of them has more leading zeros using Bitwise operation. If both the no. have the same no. of leading zeros, print "Equal".Note:- A leading zero is any 0 digit that comes before the first nonzero digit in the binary notation of the number.Examples: Input : 10, 16Output :10Explanation: If
8 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 the above two functionalities can help us achieve
5 min read
Python - Remove leading 0 from Strings List
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 compr
5 min read
Check if the given array can be reduced to zeros with the given operation performed given number of times
Given an array arr[] of N integers and an integer K, the task is to find whether the given array elements can be made 0 if the given operation is applied exactly K times. In a single operation, the smallest element from the array will be subtracted from all the non-zero elements of the array.Examples: Input: arr[] = {1, 1, 2, 3}, K = 3 Output: Yes
6 min read
Remove trailing zeros from the sum of two numbers ( Using Stack )
Given two numbers A and B, the task is to remove the trailing zeros present in the sum of the two given numbers using a stack. Examples: Input: A = 124, B = 186Output: 31Explanation: Sum of A and B is 310. Removing the trailing zeros modifies the sum to 31. Input: A=130246, B= 450164Output : 58041 Approach: The given problem can be solved using the
6 min read
Python | Add leading K character
Sometimes, during the string manipulation, we are into a problem where we need to pad or add leading K to the string as per the requirements. This problem can occur in web development. Having shorthands to solve this problem turns to be handy in many situations. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using rjust
4 min read
Maximum number of strings that can be formed with given zeros and ones
Given a list of strings arr[] of zeros and ones only and two integer N and M, where N is the number of 1's and M is the number of 0's. The task is to find the maximum number of strings from the given list of strings that can be constructed with given number of 0's and 1's. Examples: Input: arr[] = {"10", "0001", "11100", "1", "0"}, M = 5, N = 3 Out
15+ min read
Count number of trailing zeros in Binary representation of a number using Bitset
Given a number. The task is to count the number of Trailing Zero in Binary representation of a number using bitset. Examples: Input : N = 16Output : 4Binary representation of N is 10000. Therefore,number of zeroes at the end is 4.Input : N = 8Output : 3Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach:
5 min read
Python | Add trailing Zeros to string
Sometimes, we wish to manipulate a string in such a way in which we might need to add additional zeros at the end of the string; in case of filling the missing bits or any other specific requirement. The solution to this kind of problem is always handy and is good if one has knowledge of it. Let's discuss certain ways in which this can be solved. U
6 min read
PyQt5 QSpinBox - Getting the leading value of the font
In this article we will see how we can get the leading value of the spin box's font. Leading value of the text means the distance between two baselines of lines of type. The word 'leading' originates from the strips of lead hand-typesetters used to use to space out lines of text evenly. The word leading has stuck, but essentially it's a typographer
2 min read
Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
Given a binary string of 0s and 1s. The task is to find the maximum difference between the number of 0s and number of 1s in any sub-string of the given binary string. That is maximize ( number of 0s - number of 1s ) for any sub-string in the given binary string. Examples: Input : S = "11000010001" Output : 6 From index 2 to index 9, there are 7 0s
7 min read
Count ways to split a Binary String into three substrings having equal count of zeros
Given binary string str, the task is to count the total number of ways to split the given string into three non-overlapping substrings having the same number of 0s. Examples: Input: str = "01010" Output: 4 Explanation: The possible splits are: [0, 10, 10], [01, 01, 0], [01, 0, 10], [0, 101, 0] Input: str = "11111" Output: 0 Approach: To solve the p
15+ min read
Maximum difference of zeros and ones in binary string
Given a binary string of 0s and 1s. The task is to find the length of the substring which is having a maximum difference between the number of 0s and the number of 1s (number of 0s - number of 1s). In case of all 1s print -1. Examples: Input : S = "11000010001"Output : 6From index 2 to index 9, there are 70s and 1 1s, so number of 0s - numberof 1s
15 min read
Maximize trailing zeros in product from top left to bottom right of given Matrix
Given a matrix mat[][] of dimensions N * M, the task is to print the maximum number of trailing zeros that can be obtained in the product of matrix elements in the path from the top-left cell (0, 0) to the bottom-right cell (N – 1, M – 1) of the given matrix. Only possible moves from any cell (i, j) is (i + 1, j) or (i, j + 1). Examples: Input: N =
15+ min read
Count number of trailing zeros in product of array
Given a array size of n, we need to find the total number of zeros in the product of array. Examples: Input : a[] = {100, 20, 40, 25, 4} Output : 6 Product is 100 * 20 * 40 * 25 * 4 which is 8000000 and has 6 trailing 0s. Input : a[] = {10, 100, 20, 30, 25, 4, 43, 25, 50, 90, 12, 80} Output : 13 A simple solution is simply multiply and count traili
6 min read
Maximum number of trailing zeros in the product of the subsets of size k
Given an array of size n and a positive integer k, find the maximum number of trailing zeros in the product of the subsets of size k.Examples: Input : arr = {50, 4, 20} k = 2 Output : 3 Here, we have 3 subsets of size 2. [50, 4] has product 200, having 2 zeros at the end, [4, 20] — product 80, having 1 zero at the end, [50, 20] — product 1000, havi
9 min read
Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*..
Given an integer n, the task is to find the number of trailing zeros in the function [Tex]f(n)=\prod\limits_{i = 1}^{n} i^{i} [/Tex]i.e. f(n) = 11 * 22 * 33 * ... * nn. Examples: Input: n = 5 Output: 5 f(5) = 11 * 22 * 33 * 44 * 55 = 1 * 4 * 27 * 256 * 3125 = 86400000 Input: n = 12 Output: 15 Approach: We know that 5 * 2 = 10 i.e. 1 trailing zero i
7 min read
Find d to maximize the number of zeros in array c[] created as c[i] = d*a[i] + b[i]
Given two arrays of N integers. Consider an array C, where the i-th integer will be d*a[i] + b[i] where d is any arbitrary real number. The task is to print d such that array C has maximum number of zeros and also print the number of zeros. Examples: Input: a[] = {1, 2, 3, 4, 5}, b[] = {2, 4, 7, 11, 3} Output: Value of d is: -2The number of zeros i
7 min read
Find the smallest number X such that X! contains at least Y trailing zeros.
Given an integer Y, find the smallest number X such that X! contains at least Y trailing zeros. Prerequisites - Count trailing zeroes in factorial of a number Examples: Input : Y = 2 Output : 10 10! = 3628800, which has 2 trailing zeros. 9! = 362880, which has 1 trailing zero. Hence, 10 is the correct answer. Input : Y = 6 Output : 25 25! = 1551121
5 min read