The Wayback Machine - https://web.archive.org/web/20240825193045/https://www.geeksforgeeks.org/python-add-leading-zeros-to-string/
Open In App

Python | Add leading Zeros to string

Last Updated : 09 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Python

Add leading Zeros to the string using rjust() 

This function offers a single-line way to perform this particular task. Hence can easily be employed on any string whose padding we need to be done. We can specify the amount of padding required. 

Python3




# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string :"
      + str(test_string))
 
# No. of zeros required
N = 4
 
# using rjust()
# adding leading zero
res = test_string.rjust(N +
                        len(test_string), '0')
 
# print result
print("The string after adding leading zeros : "
      + str(res))


Output

The original string :GFG
The string after adding leading zeros : 0000GFG

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

Add leading Zeros to the string using zfill() 

This is yet another way to perform this particular task, in this function we don’t need to specify the letter that we need to pad, this function is exclusively made to pad zeros internally and hence recommended. 

Python3




# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string : " + str(test_string))
 
# No. of zeros required
N = 4
 
# using zfill()
# adding leading zero
res = test_string.zfill(N + len(test_string))
 
# print result
print("The string after adding leading zeros : " + str(res))


Output

The original string : GFG
The string after adding leading zeros : 0000GFG

Add leading Zeros to the string using concatenation

In this method, we are multiplying the 0 as a string with the number of zeros the user wants and using Python concatenation to merge them all.

Python3




# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string : " +
      str(test_string))
 
# No. of zeros required
N = 4
 
 
# adding leading zero
x = '0'*N
res = x+test_string
 
# print result
print("The string after adding leading\
zeros : " + str(res))


Output

The original string : GFG
The string after adding leadingzeros : 0000GFG

Add leading Zeros to the string using formatting:

This code defines a function add_leading_zeros() that takes in a string s and an integer num_zeros and returns a new string with num_zeros number of zeros added to the start of the string.

The function uses string formatting to pad the input string s with zeros on the right side (i.e., at the start of the string). The width parameter specifies the total width of the resulting string, and the :0> part tells Python to pad the string with zeros on the right side.

The code then tests the function by initializing the string s to “GFG” and the number of zeros num_zeros to 4. It prints the original string and then calls the add_leading_zeros() function to add leading zeros to the string. The resulting padded string is then printed.

Python3




def add_leading_zeros(s, num_zeros):
    # use string formatting to pad the string with zeros
    formatted_string = "{:0>{width}}".format(s, width=num_zeros + len(s))
    return formatted_string
 
# test the function
s = "GFG"
num_zeros = 4
 
# print the original string
print("The original string :", s)
 
# add leading zeros to the string
padded_string = add_leading_zeros(s, num_zeros)
 
# print the padded string
print("The string after adding leading zeros :", padded_string)
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original string : GFG
The string after adding leading zeros : 0000GFG

Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), since a new string is created to store the padded string.

Add leading zeroes to string using while loop and += operator

Python3




s = "GFG"
num_zeros = 4
 
# print the original string
print("The original string :", s)
 
# add leading zeros to the string
i=0
padded_string=""
while(i<num_zeros):
    padded_string+="0"
    i+=1
     
padded_string+=s
# print the padded string
print("The string after adding leading zeros :", padded_string)


Output

The original string : GFG
The string after adding leading zeros : 0000GFG

Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), since a new string is created to store the padded string.

Another Method:

The below implementation uses the multiplication operator to create a string of leading zeroes with the number of zeroes equal to the desired leading_zero minus the length of the input string, and concatenates it with the original string.

Python3




def add_leading_zeroes(s, leading_zero):
    return f"{'0'*leading_zero}{s}"
 
 
# Test the function
s = "GFG"
leading_zero = 4
 
# print the original string
print("The original string :", s)
print("The string after adding leading zeros :", add_leading_zeroes(s, leading_zero))


Output

The original string : GFG
The string after adding leading zeros : 0000GFG

Time Complexity: O(1)
Auxiliary Space: O(n), as we are creating a new string with n zeroes.

Add leading Zeros to the string using string.ljust() method:

1.Initialize the input string ‘test_string’.
2.Print the original string using the print() function.
3.Initialize the number of zeros required ‘N’.
4.Use the ljust() method of the input string to add leading zeros.
a. The first argument to the ljust() method is the total width of the resulting string, which is the sum of the length of the input string and the number of zeros required.
b. The second argument is the character to be used for padding, which is ‘0’ in this case.
5.Store the resulting string in the variable ‘res’.
6.Print the resulting string using the print() function.

Python3




# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string: " + test_string)
 
# number of zeros required
N = 4
 
# using ljust()
# adding leading zeros
res = test_string.ljust(N + len(test_string), '0')
 
# print result
print("The string after adding leading zeros: " + res)


Output

The original string: GFG
The string after adding leading zeros: GFG0000

Time Complexity:
The time complexity of the given code is O(N), since the ljust() method performs a single pass over the input string.

Space Complexity:
The space complexity of the given code is O(N), where N is the number of zeros required, since the resulting string may have up to N extra characters due to the leading zeros.

Adding leading zeroes to the string using itertools.repeat() and join() methods

Approach

  1. Used itertools.repeat() to repeat ‘0’ N times and the join the object returned by empty string(using join method)
  2. Concatenate the joined string and test_string and store it in res
  3. Display res

Python3




import itertools
# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string: " + test_string)
 
# number of zeros required
N = 4
 
# adding leading zeros
res= "".join(itertools.repeat("0",N))+test_string
 
# print result
print("The string after adding leading zeros: " + res)


Output

The original string: GFG
The string after adding leading zeros: 0000GFG

Time Complexity : O(N) N – value of N

Auxiliary Space : The space complexity of the given code is O(N), where N is the number of zeros required, since the resulting string may have up to N extra characters due to the leading zeros.



Similar Reads

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
Python Program for 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
3 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
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
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
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
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
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
Create a Numpy array filled with all zeros | Python
In this article, we will learn how to create a Numpy array filled with all zeros, given the shape and type of array. We can use Numpy.zeros() method to do this task. This method takes three parameters, discussed below - shape : integer or sequence of integers order : C_contiguous or F_contiguous C-contiguous order in memory(last index varies the fa
2 min read
numpy.matlib.zeros() function | Python
numpy.matlib.zeros() function return matrix of given shape and type, filled with zeros. Syntax : numpy.matlib.zeros(shape, dtype = None, order = 'C') Parameters : shape : [sequence of ints] Shape of the empty matrix. dtype : [data-type, optional] The desired data-type for the matrix, default is float. order : [{‘C’, ‘F’}, optional] Whether to store
1 min read
Python PyTorch zeros() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.zeros() returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size. Syntax: torch.zeros(size, out=None) Parameters: size: a sequence of i
1 min read
How to Create Array of zeros using Numpy in Python
In this article, we will cover how to create a Numpy array with zeros using Python. Python Numpy Zeros Array In Numpy, an array is a collection of elements of the same data type and is indexed by a tuple of positive integers. The number of dimensions in an array is referred to as the array's rank in Numpy. Arrays in Numpy can be formed in a variety
2 min read
numpy.zeros() in Python
The numpy.zeros() function returns a new array of given shape and type, with zeros. Syntax: numpy.zeros(shape, dtype = None, order = 'C')Parameters : shape : integer or sequence of integersorder : C_contiguous or F_contiguous C-contiguous order in memory(last index varies the fastest) C order means that operating row-rise on the array will be sligh
2 min read
Python | sympy.zeros() method
With the help of sympy.zeros() method, we can create a matrix having dimension nxm and filled with zeros by using sympy.zeros() method. Syntax : sympy.zeros() Return : Return a zero matrix. Example #1 : In this example, we can see that by using sympy.zero() method, we are able to create the zero matrix having dimension nxn all filled with zeros, wh
1 min read
numpy matrix operations | zeros() function
numpy.matlib.zeros() is another function for doing matrix operations in numpy. It returns a matrix of given shape and type, filled with zeros. Syntax : numpy.matlib.zeros(shape, dtype=None, order='C') Parameters : shape : [int, int] Number of rows and columns in the output matrix.If shape has length one i.e. (N, ), or is a scalar N, out becomes a s
2 min read
Mahotas - Fraction of zeros in image
In this article we will see how we can get the fraction of zeros in the image in mahotas. Fraction of zeros is the percentage amount of statistical data which is zero. It is relevant in statistical models where a significant amount of objects has zero value.In this tutorial we will use "luispedro" image, below is the command to load it. mahotas.dem
2 min read
Replace Negative Number by Zeros in Pandas DataFrame
In this article, Let's discuss how to replace the negative numbers by zero in Pandas Approach: Import pandas module.Create a Dataframe.Check the DataFrame element is less than zero, if yes then assign zero in this element.Display the final DataFrame First, let's create the dataframe. C/C++ Code # importing pandas module import pandas as pd # Creati
1 min read
Replace NaN Values with Zeros in Pandas DataFrame
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results.  Methods to Replace NaN V
5 min read
Python - Add Phrase in middle of String
Given a String, add a phrase in the middle of it. Input : test_str = 'geekforgeeks is for geeks', mid_str = "good" Output : geekforgeeks is good for geeks Explanation : Added just in middle, after 2 words. Input : test_str = 'geekforgeeks best', mid_str = "is" Output : geekforgeeks is best Explanation : Added just in middle, after 1 word. Method #1
7 min read
Python - Add space between Numbers and Alphabets in String
In this article, we delve into a practical Python solution to improve text readability by adding spaces between numbers and alphabets in strings by utilizing Python's powerful string manipulation capabilities. Input: test_str = 'ge3eks4geeks is1for10geeks' Output: ge 3 eks 4 geeks is 1 for 10 geeks Explanation: Numbers separated from Characters. Ad
9 min read
Add padding to a string in Python
Inserting non-informative characters into a string is known as Padding. The insertion can be done anywhere on the string. String padding is useful for output formatting and alignment of strings while printing. Even for displaying values like a table string Padding is required. In this article, we will see how to Pad Zeros to a String in Python. Dif
4 min read
Python | Add one string to another
The concatenation of two strings has been discussed multiple times in various languages. But the task is how to add to a string in Python or append one string to another in Python. Example Input: 'GFG' + 'is best' Output: 'GFG is best' Explanation: Here we can add two string using "+" operator in PythonAppend a String in Python Python Strings are i
5 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python - Add values to Dictionary of List
In this article, we will discuss how to add values to the dictionary of lists. We can add values to a dictionary by using a list, the input list would be the following structure: [('key',value),...........,('key',value)] So the above list is an input, which we can use with for loop to add values to the dictionary of lists. Syntax: for key, value in
2 min read
Python Program to Split the array and add the first part to the end
There is a given array and split it from a specified position, and move the first part of the array add to the end. Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end .Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explana
5 min read
Add packages to Anaconda environment in Python
Let's see some methods that can be used to install packages in the Anaconda environment. There are many ways one can add pre-built packages to an anaconda environment. So, let's see how to direct the path in the anaconda and install them. Add packages to the Anaconda environment using the navigator Step 1: Open your Anaconda navigator Step 2: Go to
2 min read
Python | Pandas Series.add()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Python Series.add() is used to add series or list like objects with same length to the caller series. Syntax: Series.add(other, level=No
2 min read
Python | Pandas dataframe.add()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Dataframe.add() method is used for addition of dataframe and other, element-wise (binary operator add). Equivalent to dataframe + other,
3 min read
Practice Tags :