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.
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 ().
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.
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:
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:
Method :Using the % operator with the 0 flag:
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
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.
Please Login to comment...