0
0
PythonHow-ToBeginner · 3 min read

How to Use ljust and rjust in Python for Text Alignment

In Python, ljust(width, fillchar) returns a string left-aligned in a field of given width, padding with fillchar (default is space). Similarly, rjust(width, fillchar) returns a right-aligned string padded to the specified width.
📐

Syntax

The ljust and rjust methods are called on strings to align text by adding padding characters.

  • string.ljust(width, fillchar=' '): Returns the string left-aligned in a field of length width. Pads on the right with fillchar.
  • string.rjust(width, fillchar=' '): Returns the string right-aligned in a field of length width. Pads on the left with fillchar.
  • width must be an integer greater than or equal to the string length.
  • fillchar is optional and must be a single character string; default is space.
python
text = 'Hi'
left_aligned = text.ljust(5, '*')
right_aligned = text.rjust(5, '-')
print(left_aligned)
print(right_aligned)
Output
Hi*** ---Hi
💻

Example

This example shows how to use ljust and rjust to align words in a simple table format by padding with spaces.

python
words = ['cat', 'dog', 'elephant']
for word in words:
    print(word.ljust(10) + '|' + word.rjust(10))
Output
cat | cat dog | dog elephant | elephant
⚠️

Common Pitfalls

Common mistakes include:

  • Using a width smaller than the string length, which returns the original string without padding.
  • Passing a fillchar longer than one character, which raises a TypeError.
  • Confusing ljust and rjust roles (left vs right alignment).
python
text = 'hello'
# Wrong: fillchar longer than one character
try:
    print(text.ljust(10, 'ab'))
except TypeError as e:
    print('Error:', e)

# Right: single character fillchar
print(text.ljust(10, '-'))
Output
Error: The fill character must be exactly one character long hello-----
📊

Quick Reference

MethodPurposeParametersExample
ljust(width, fillchar=' ')Left-align stringwidth: int, fillchar: single char'Hi'.ljust(5, '*') → 'Hi***'
rjust(width, fillchar=' ')Right-align stringwidth: int, fillchar: single char'Hi'.rjust(5, '-') → '---Hi'

Key Takeaways

Use ljust to left-align and rjust to right-align strings by padding with a character.
The width must be at least the string length; otherwise, the original string is returned.
The fill character must be a single character string, defaulting to space if omitted.
Passing a fill character longer than one character causes a TypeError.
ljust pads on the right; rjust pads on the left.