Python Padding | How to Pad Zeros to Number or String?
Many times to represent the data or display it on the output console, we need to pad a number with extra zeros to make it looks consistent.
In this post, I a going to share simplest two methods for Python padding.
Before jumping into the code, let’s see…
If you have the serial number from 0 to 999. It looks something like this…
0 1 2 . . 8 9 . . 25 26 17 . . 997 998 999
The number series does not look fancy as the length of the number in the series varies. If we pad the number to make it have the same length (says 3), it looks like this…
If we pad the number to make it have the same length (says 3), it looks like this…
000 001 002 . . 008 009 . . 025 026 017 . . 997 998 999
From above two number series list, which one does look good?
I am sure, its Second!
So let’s see how to pad integer number and string in Python.
There are multiple methods of doing this. Let’s check some of the simple Python tricks…
Method 1: Using zfill()
strNum = '7' print strNum.zfill(3)
The zfill is a function associated with the string object. 3 is the expected length of the string after padding.
Method 2: Using rjust()
strNum = '7' strNum.rjust(3, '0')
The rjust() is string inbuilt function in Python. Pass the expected the length of the string after padding and character to be used for padding as two parameters of the function.
With this function, you can use any character for padding.
Both the method will give the same output as…
“1” gives out as a string of “001”
“2” gives “002”, “99” gives “099”, “100” gives “100”, “999” gives “999”
Exception: If the length of the given string is greater than the padding length, it returns the same string.
Above code returns “7000” for “7000” even if you pass 3 as expected length after padding.
In Python, you can not pad integer number. You have to convert the number into the string. And then pad it.
Conversion of the integer into the string is very easy.
num = 7 strNum = str(num)
Now you can make the consistent length for all the numer in series.
This function will be more helpful if you have a function that manipulates the same length of the input string.
Other Python Tricks:
- Swap Two Variables without using Third Variable [in just one line of code]
- Get all the Permutations of String
- Reverse String in Python [using Extended Slice Syntax ]
This is all about Python padding. There are so many other methods of doing this. To make it simple to use in your code, I have listed simplest two methods.
If you think as there are other simplest ways of solving this problem, comment below. I am sure it will be helpful other Python Programmers.