Add padding to a Python string
This post will discuss how to add padding to a string in Python.
1. Using str.rjust() function
The standard way to add padding to a string in Python is using the str.rjust() function. It takes the width and padding to be used. If no padding is specified, the default padding of ASCII space is used.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = 'ABC' padding = 'X' len = 8 x = s.rjust(len, padding) print(x) # XXXXXABC |
2. Using str.zfill() function
Another option to convert a string to a specified length left-padded with zeros is using the str.zfill() function. It is different from the rjust function, which allows you to specify the padding to be used, while the zfill function always fills the string with ASCII digit 0.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = 'ABC' len = 8 x = s.zfill(len) print(x) # 00000ABC |
3. Using str.format() function
Besides the rjust() and zfill() function, you can use general string formatting. You can do this with the str.format() function, which works for both numbers and strings.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = 'ABC' padding = 'X' len = 8 x = ('{:' + padding + '>' + str(len) + '}').format(s) # x = '{:X>8}'.format(s) print(x) # XXXXXABC |
4. Using f-strings
Starting with Python 3.6, you can use f-strings. Here’s how the code would look like which works with both numbers and strings:
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = 'ABC' padding = 'X' len = 8 x = f'{s:{padding}>{len}}' # x = f'{s:X>8}' print(x) # XXXXXABC |
5. Using format() function
Finally, you can use the built-in function format() for adding padding to a string or a number. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = 'ABC' padding = 'X' len = 8 x = format(s, padding + '>' + str(len)) # x = format(s, 'X>8') print(x) # XXXXXABC |
That’s all about adding padding to a string 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 :)