Python String rjust: Right-Aligning Text
python string rjust: Learn how str.rjust() right-aligns strings in Python, including custom fill characters, edge cases, and when format specifiers are a better choice.
python string rjust requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.
Python's str.rjust() method returns a right-aligned copy of a string, padded on the left to a specified width. It is part of the standard string API and requires no imports. The method does not modify the original string; it returns a new one.
Core Syntax and Return Behavior
The signature is:
str.rjust(width[, fillchar])
width is an integer specifying the total length of the returned string. fillchar is an optional single-character string used for padding; it defaults to a space.
code = "42" aligned = code.rjust(6) print(repr(aligned)) # ' 42'
The returned string has length 6, with four spaces prepended. The original code variable is unchanged because strings are immutable in Python.
The method always returns a new string object. Even when no padding is needed, the result is a separate string, although CPython may reuse the original object internally in some cases. Relying on that optimization is not part of the language contract.
What Happens When the Width Is Too Small
If the string is already as long as or longer than width, rjust() returns the string unchanged:
print("42".rjust(2)) # '42' print("42".rjust(1)) # '42' print("longer".rjust(4)) # 'longer'
There is no truncation. This behavior matters when you align dynamic data: a value that exceeds the column width will push the column wider rather than being cut off. If truncation is required, you must slice the string explicitly before calling rjust():
value = "123456" print(value[:5].rjust(6)) # ' 12345'
Choosing a Custom Fill Character
The optional second argument replaces the default space padding:
print("42".rjust(6, "0")) # '000042' print("42".rjust(6, ".")) # '....42'
The fillchar argument must be exactly one character. Passing a multi-character string raises ValueError:
"42".rjust(6, "ab") # ValueError: The fill character must be exactly one character long
This constraint is enforced at call time, so it is worth validating input when the fill character comes from configuration or user input rather than a literal in the code.
Practical Use Cases for Right-Aligned Text
Right alignment is most useful when presenting numbers in columns so that digit positions line up visually. A common pattern is formatting a list of values into a fixed-width column:
values = [3, 42, 512, 7] for value in values: print(str(value).rjust(4))
Output:
3
42
512
7
The same approach works for building log lines or report rows where each field occupies a consistent width. Because rjust() returns a plain string, the result can be combined with other string operations or written directly to a file:
with open("report.txt", "w") as f: for value in values: f.write(str(value).rjust(4) + "\n")
One limitation is that rjust() operates on the string representation you give it. If you pass a number directly, it fails with AttributeError because integers do not have a rjust method. Convert to str() first, or use a format specifier as described below.
Comparing rjust with ljust, center, and zfill
Python provides several related alignment methods. The choice depends on the visual layout you need:
| Method | Alignment | Padding side | Typical use |
|---|---|---|---|
rjust() | Right | Left | Numbers, right-aligned columns |
ljust() | Left | Right | Labels, left-aligned columns |
center() | Centered | Both sides | Headings, titles |
zfill() | Right | Left, zeros | Fixed-width numeric codes |
zfill() is a special case of right alignment that pads with zeros and handles a leading sign correctly:
print("-42".zfill(6)) # '-00042'
The equivalent rjust() call would place the sign after the padding:
print("-42".rjust(6, "0")) # '000-42'
If you are formatting numeric identifiers, order numbers, or any value where a leading minus sign must stay at the front, zfill() is the safer choice.
rjust vs. Format Specifiers and f-Strings
The same right alignment can be expressed with format specifiers:
value = 42 print(f"{value:>6}") # ' 42' print("{:>6}".format(value)) # ' 42'
Format specifiers accept a fill character before the alignment operator:
print(f"{value:0>6}") # '000042'
The format-specifier approach has two advantages. First, it works directly on integers and floats without an explicit str() conversion. Second, the alignment is visible at the call site, which can make the intent clearer when the formatting rule is part of a larger f-string:
print(f"ID: {value:0>6} Status: {status:<10}")
Use rjust() when you already have a string and want a simple method call, or when the padding rule is computed dynamically. Use format specifiers when you are formatting values inline and want the expression to stay compact.
Performance and Maintainability Considerations
rjust() creates a new string of length max(len(s), width) and copies the original content into it. The operation is linear in the output size and runs in C, so it is fast for typical string lengths. There is no meaningful performance risk in calling it repeatedly for report rows or log lines.
The more important consideration is maintainability. Mixing rjust(), ljust(), and manual concatenation in the same codebase makes alignment rules harder to spot. If a module formats several columns, prefer one consistent mechanism, either the alignment methods or format specifiers, so that a future change to column width touches one place rather than scattered calls.
A second maintainability point concerns the fill character. When the fill character is a literal in the code, a typo such as a two-character string raises ValueError at runtime. If the fill character comes from a configuration value, validate it once at startup rather than letting the error surface mid-processing.
Finally, remember that rjust() does not truncate. If your report format requires a maximum column width, apply slicing before alignment and document that behavior explicitly, because the default no-truncation behavior is easy to overlook when data grows unexpectedly.