When outputting data in a table format to the console (terminal) or formatting logs for better readability, aligning text is an essential task.
Python strings come with three built-in methods to adjust the position of a string within a specified width: rjust(), ljust(), and center(). These methods allow you to fill the empty space with a specific character (the default is a space).
In this article, I will explain how to use each method and how to specify the padding character.
Table of Contents
- Right Align:
rjust() - Left Align:
ljust() - Center Align:
center() - Advanced: Using f-strings
- Summary
1. Right Align: rjust()
rjust() (Right Justify) aligns the string to the right end and fills the left side with a specified character.
Syntax:
new_string = original_string.rjust(total_width, fill_character)
Note: If the fill character is omitted, a half-width space is used.
Usage Example
text = "abc"
# Set total width to 6, fill left side with "*"
right_aligned = text.rjust(6, "*")
print(f"Original: '{text}'")
print(f"Right : '{right_aligned}'")
Execution Result:
Original: 'abc'
Right : '***abc'
The total width became 6 characters, and the 3 characters on the left were filled with *.
2. Left Align: ljust()
ljust() (Left Justify) aligns the string to the left end and fills the right side with a specified character.
Syntax:
new_string = original_string.ljust(total_width, fill_character)
Usage Example
text = "abc"
# Set total width to 6, fill right side with "*"
left_aligned = text.ljust(6, "*")
print(f"Left : '{left_aligned}'")
Execution Result:
Left : 'abc***'
3. Center Align: center()
center() places the string in the middle and fills both sides with a specified character.
Syntax:
new_string = original_string.center(total_width, fill_character)
Usage Example
text = "abc"
# Set total width to 6, fill both sides with "*"
centered = text.center(6, "*")
print(f"Center : '{centered}'")
Execution Result:
Center : '*abc**'
If the remainder (total width minus string length) is an odd number (in this example, 6 – 3 = 3), Python adjusts it so that the right side gets one extra character.
Advanced: Using f-strings
In Python 3.6 and later, you can achieve the same result using f-string formatting. This is often used in modern code because it is intuitive when embedding variables.
<: Left align>: Right align^: Center align
text = "abc"
width = 6
fill = "*"
# Format: {value : fill align width}
print(f"Right : '{text:*>6}'")
print(f"Left : '{text:*<6}'")
print(f"Center: '{text:*^6}'")
Execution Result:
Right : '***abc'
Left : 'abc***'
Center: '*abc**'
Summary
rjust(width, char): Right align (fill the left side).ljust(width, char): Left align (fill the right side).center(width, char): Center align (fill both sides).- If the character argument is omitted, spaces are used.
- The same results can be achieved using f-string formatting (
<,>,^).
