Add padding to a number in Python
This post will discuss how to add padding to a number in Python.
1. Using str.rjust() function
A simple approach to add padding to a number is using the str.rjust() function, which takes the length and the fill character.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': i = 1111 pad = '0' n = 8 x = str(i).rjust(n, pad) print(x) # 00001111 |
2. Using str.zfill() function
Another alternative to convert a number to a specified length left-padded with 0’s is using the str.zfill() function.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': i = 1111 n = 8 x = str(i).zfill(n) print(x) # 00001111 |
3. Using f-strings
Starting with Python 3.6, you can use f-strings.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': i = 1111 pad = '0' n = 8 x = f'{i:{pad}{n}}' # x = f'{i:08}' print(x) # 00001111 |
4. Using str.format() function
Before Python 3.6, you can use general string formatting with the str.format() function.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': i = 1111 pad = '0' n = 8 x = ('{:' + pad + str(n) + '}').format(i) # x = '{:08}'.format(i) print(x) # 00001111 |
5. Using built-in format() function
Finally, you can use the built-in function format() to add padding to a number.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': i = 1111 pad = '0' n = 8 x = format(i, pad + str(n)) # x = format(i, '08') print(x) # 00001111 |
That’s all about adding padding to a number in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)