When it comes to python string padding, there are a few different methods you can use. These methods are
Table of Contents
When it comes to python string padding, there are a few different methods you can use. These methods are
- ljust()
- rjust()
- center()
All three of these methods take an optional second parameter to specify the padding character. If you don’t specify a padding character, the default is a space.
Method 1: Padding to the Right or End of the String
The first method is ljust(), which will left-justify your string within the given field size. ljust() function is used to add padding to the end of the string.
Example 1:
In this example, we pad a string with spaces to a fixed length of 20 using ljust().
str = "AiOcta"
print(str.ljust(20))
Output:
AiOcta
Example 2:
You can also add any character to the end of the string using ljust(). In this example, we pad the string with “-” symbol.
str = "AiOcta"
print(str.ljust(20, "-"))
Output:
AiOcta--------------
Method 2: Padding to the Left or Start of the String
The second method is rjust(), which does the same thing but right-justifies the string.
Example 1:
A whitespace padding with a fixed length of 20 is used at the start of the string.
str = "AiOcta"
print(str.rjust(20))
Output:
AiOcta
Example 2:
In this example, we used zero padding instead of whitespace padding. We also changed the character length parameter from 20 to 30.
str = "AiOcta"
print(str.rjust(30, "0"))
Output:
000000000000000000000000AiOcta
Method 3: Padding to the Both Side of the String
There’s also center(), which, you guessed it, centers the string within the given field size. In this example, we used 20 characters in length and filled the padding with dashes “-“.
str = "AiOcta"
print(str.center(20, "-"))
Output:
-------AiOcta-------
Additional Method: Add Padding using zfill()
you can also use the zfill() method. This method will add zeros to the left of the string until it reaches the given field size.
Example:
str = "AiOcta"
print(str.zfill(20))
Output:
00000000000000AiOcta
References: