There are 2 main ways we can add padding to a string in Python-
Method #1: String Padding Functions
Use the string functions like “ljust()“, “rjust()“, “center()“, “zfill()” to get the desired width by adding some padding to the string.
str.ljust() - left justify original
Use the “ljust()” function to left justify the original string. Here is the signature of “ljust()” function-
str.ljust(self, __width: int, __fillchar: str = ...) -> str
Pythonname = "BigBoxCode"
result = name.ljust(20)
print(f"-{result}-")
result = name.ljust(20, "*")
print(f"-{result}-")
PythonOutput:
-BigBoxCode -
-BigBoxCode**********-
Plaintextname = "BigBoxCode"
result = name.ljust(20, "*9")
print(f"-{result}-")
PythonOutput:
Traceback (most recent call last):
File "bigboxcode.py", line 3, in <module>
result = name.ljust(20, "*9")
TypeError: The fill character must be exactly one character long
Plaintextstr.rjust() - right justify original
We can use “rjust()” to right justify the original string. Here is the signature of “rjust()” function-
str.rjust(self, __width: int, __fillchar: str = ...) -> str
Pythonname = "BigBoxCode"
result = name.rjust(20, "*")
print(f"-{result}-")
PythonOutput:
-**********BigBoxCode-
Plaintextstr.center()
Use “center()” function to center justify the original string. Here is the signature-
str.center(self, __width: int, __fillchar: str = ...) -> str
Pythonname = "BigBoxCode"
result = name.center(20, "*")
print(f"-{result}-")
PythonOutput:
5 fill characters are added on the left and 5 on the right.
-*****BigBoxCode*****-
Plaintextname = "BigBoxCode"
result = name.center(21, "*")
print(f"-{result}-")
PythonOutput:
6 fill characters are added on the left and 5 on the right.
-******BigBoxCode*****-
Plaintextstr.zfill() - fill with zero
Use “zfill()” to fill the string with zeros(0), to achieve the desired width. Here is the signature of zfill-
str.zfill(self, __width: int) -> str
Pythonnum = "23"
result = num.zfill(4)
print(result)
PythonOutput:
Our original string is “23” and 2 zeros are added in the front to make it of width of 4.
0023
PlaintextMethod #2: f – String
We can set the string padding, while using a string formatting.
< - left align original string
name = "BigBoxCode"
print(f"-{name:<20}-")
print(f"-{name:*<20}-")
PythonOutput:
-BigBoxCode -
-BigBoxCode**********-
Plaintext> - right align original string
name = "BigBoxCode"
print(f"-{name:>20}-")
print(f"-{name:*>20}-")
PythonOutput:
- BigBoxCode-
-**********BigBoxCode-
Plaintext^ - center align original string
name = "BigBoxCode"
print(f"-{name:^20}-")
print(f"-{name:*^20}-")
print(f"-{name:*^21}-")
PythonOutput:
If an odd number is used as width, then the right part has 1 more fill character than the right.
Here in the last example, we have used 21 as desired width. So, 5 asterisks(*) are used on the left and 6 on the right.
- BigBoxCode -
-*****BigBoxCode*****-
-*****BigBoxCode******-
Plaintext