Alignment Methods in Python
In Python, alignment methods are used to format strings by aligning them to the center, left, or right within a specified width. These methods are especially useful in formatting output for tables, menus, or visual displays.
1. center() Method
Returns a new string that is center-aligned in a string of specified width. Extra space is filled with optional characters like *, -, + etc (default is space).
Syntax:
string.center(width, fillchar)
Example:
text = "Python"
print(text.center(11))
print(text.center(11, '*'))
Output:
Python
**Python***
Explanation:
- Width = 11 means the total string length becomes 11.
- Original string "Python" has 6 characters, so 5 extra spaces are added (or fill characters).
- These are equally distributed on both sides to center the text.
2. ljust() Method
Returns a new string that is left-aligned in a string of specified width. Extra space is filled with optional characters like *, -, + etc (default is space).
Syntax:
string.ljust(width, fillchar)
Example:
text = "Python"
print(text.ljust(10))
print(text.ljust(10, '-'))
Output:
Python
Python----
Explanation:
ljust()adds extra space or fill characters to the right side.- The original text remains on the left.
3. rjust() Method
Returns a new string that is right-aligned in a string of specified width. Extra space is filled with optional characters like *, -, + etc (default is space).
Syntax:
string.rjust(width, fillchar)
Example:
text = "Python"
print(text.rjust(10))
print(text.rjust(10, '.'))
Output:
Python
....Python
Explanation:
rjust()adds padding to the left side of the string.- The original text is pushed to the right.
4. zfill() Method
Returns a new string of the specified width where the original string is right-aligned and the left side is padded with zeros (0) instead of spaces or other characters.
Syntax:
string.zfill(width)
Example:
text = "42"
print(text.zfill(5))
text2 = "-42"
print(text2.zfill(6))
Output:
00042
-00042
Explanation:
zfill()adds zeros to the left side to make the total width as given.- If the string contains a negative sign, the zeros are placed after the minus sign.
- It is mostly used when formatting numbers or IDs with fixed width.
String Alignment & Padding Methods - Summary Table
| Method | Purpose | Padding Side | Default Fill | Custom Fill? |
|---|---|---|---|---|
center(width, fillchar) |
Center-align the string | Both Sides | Space | Yes |
rjust(width, fillchar) |
Right-align the string | Left | Space | Yes |
ljust(width, fillchar) |
Left-align the string | Right | Space | Yes |
zfill(width) |
Right-align with zero-padding | Left (after minus sign) | 0 | No |