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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

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:

Download  Run Code

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:

Download  Run Code

That’s all about adding padding to a string in Python.