How to Add leading Zeros to a Number in Python
Last Updated :
24 Mar, 2023
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 Python
Add leading Zeros to numbers using format()
For more effective handling of sophisticated string formatting, Python has included the format() method. A formatter inserts one or more replacement fields and placeholders into a string by using the str.format function and a pair of curly braces ().
Python3
print("{:03d}".format(1))
print("{:05d}".format(10))
Add leading Zeros to the number using f-string
Prefix the string with the letter "f" to get an f-string. The string itself can be prepared similarly to how str.format would be used (). F-strings offer a clear and practical method for formatting python expressions inside of string literals.
Python3
num1 = 16
print(f" {num1 : 03d} ")
print(f" {num1 : 07d} ")
Add zeros using rjust() method :
One approach that is not mentioned in the article is using the rjust() method of the built-in str class to add leading zeros to a number. The rjust() method returns a right-justified string, with optional padding, based on a specified width.
Here is an example of how you could use the rjust() method to add leading zeros to a number:
Python3
num = 11
padded_num = str(num).rjust(6, '0')
print(padded_num) # Output: 000011
Using the rjust() method can be a simple and concise way to add leading zeros to a number, especially if you only need to pad the number with a fixed number of zeros. It is also useful if you need to pad a number that is stored as a string, as it works directly on strings.
Note that the rjust() method returns a new string, so you will need to store the padded number in a separate variable if you want to keep it.
Add zeros using zfill() method :
The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.
Below is the implementation:
Python3
num = '42'
ans = num.zfill(8)
print(ans)
Method :Using the % operator with the 0 flag:
Python3
num = 42
res = "%06d" % num
print(res)
Add zeros using join() method :
- Converting the number to a string using the str()
- Finding the length of the string using the len().
- The join() method is commonly concatenate a sequence of strings with a specified separator
- Concatenating the list of zeros and the original string using the + operator
- Assigning the result to padded_num
Python3
num = 11
padded_num = "".join(["0"] * (6 - len(str(num)))) + str(num)
print(padded_num) # Output: 000011
Time complexity: O(n), where n is the number of zeros to be added.
Space Complexity: O(n), where n is the number of zeros to be added.
Similar Reads
How to Round Numbers in Python? Rounding a number simplifies it while keeping its value as close as possible to the original. Python provides various methods to round numbers, depending on how we want to handle the precision or rounding behavior. In this article, we'll cover the most commonly used techniques for rounding numbers i
4 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
4 min read
How to Create Array of zeros using Numpy in Python numpy.zeros() function is the primary method for creating an array of zeros in NumPy. It requires the shape of the array as an argument, which can be a single integer for a one-dimensional array or a tuple for multi-dimensional arrays. This method is significant because it provides a fast and memory
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 a
4 min read
How to convert string to integer in Python? In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
3 min read
Python Program to Count trailing zeroes in factorial of a number Given an integer n, write a function that returns the count of trailing zeroes in n! Examples : Input: n = 5 Output: 1 Factorial of 5 is 120 which has one trailing 0. Input: n = 20 Output: 4 Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100 Output: 24Trailing 0s in n
4 min read
How to find the int value of a string in Python? In Python, we can represent an integer value in the form of string. Int value of a string can be obtained by using inbuilt function in python called as int(). Here we can pass string as argument to this function which returns int value of a string. int() Syntax : int(string, base) Parameters : strin
2 min read
How to remove all decimals from a number using Python? We have to remove all decimals from a number and get the required output using Python. There are several ways to achieve this, depending on whether you want to simply truncate the decimal part, round it or perform other manipulations. For example, number is 12.345 then result is 12.Using int( )int(
3 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. Let's understand with the help of an example:Pythonimport numpy as np # Create a 1D array of zeros with 5 elements array_1d = np.zeros
2 min read
numpy.trim_zeros() in Python numpy.trim_zeros function is used to trim the leading and/or trailing zeros from a 1-D array or sequence. Syntax: numpy.trim_zeros(arr, trim) Parameters: arr : 1-D array or sequence trim : trim is an optional parameter with default value to be 'fb'(front and back) we can either select 'f'(front) and
2 min read