Python String ljust: Align Text with Custom Padding
python string ljust: Learn how to use Python's str.ljust() to pad strings with spaces or custom characters for aligned console output and clean formatting.
When you need to align text in console output or generate fixed-width columns, Python's str.ljust() method is a direct tool. This article covers the python string ljust method, its parameters, behavior, and practical use cases.
Syntax and Parameters
The ljust() method is available on every Python string. Its signature is:
str.ljust(width, fillchar=' ')
widthis an integer specifying the total length of the resulting string.fillcharis an optional single character used for padding. It defaults to a space.
The method returns a new string of length max(len(original), width). If the original string is already at least width characters long, it is returned unchanged. Otherwise, the string is padded on the right with fillchar until it reaches width.
name = "Ada" print(name.ljust(10)) # Output: "Ada "
The result is a new string; the original is not modified because strings are immutable.
How ljust Behaves When the String Exceeds Width
A common misunderstanding is that ljust() truncates the string when it exceeds the given width. It does not. The method only adds padding; it never removes characters.
text = "longer than width" print(len(text)) # 17 print(text.ljust(10)) # "longer than width" (unchanged)
This behavior is useful when you want to enforce a minimum width without losing data. If you need truncation, you must slice the string manually or use a formatting specifier like {:.10}.
Aligning Columns in Console Output
A typical use case is printing tabular data where each column should have a consistent width. Without alignment, columns become ragged and hard to read.
rows = [ ("Alice", 30, "Engineer"), ("Bob", 25, "Designer"), ("Carol", 35, "Manager") ] for name, age, role in rows: print(name.ljust(10) + str(age).ljust(5) + role)
Output:
Alice 30 Engineer
Bob 25 Designer
Carol 35 Manager
Here ljust() ensures the name column occupies 10 characters and the age column 5 characters. The role starts at the same position on each line, making the output easy to scan.
Using a Custom Fill Character
The fillchar parameter lets you pad with something other than spaces. This is often used for visual separators or decorative output.
print("Section".ljust(20, "-")) # Output: "Section-------------"
You can also use it to create a simple progress bar or a divider line. The fillchar must be exactly one character; passing a longer string raises a TypeError.
try: "text".ljust(10, "--") except TypeError as e: print(e) # The fill character must be exactly one character long
Comparing ljust, rjust, and center
Python provides three related methods for horizontal alignment:
| Method | Alignment | Padding Side |
|---|---|---|
ljust() | Left | Right |
rjust() | Right | Left |
center() | Center | Both |
All three accept the same width and fillchar arguments. The choice depends on the visual effect you need. For numbers, right-alignment is often preferable because it keeps digits aligned by place value. For labels, left-alignment is typical.
value = 42 print(str(value).rjust(5)) # " 42" print(str(value).center(5)) # " 42 "
Performance and Memory Considerations
ljust() creates a new string every time it is called. For small strings and moderate output, this is irrelevant. But in a loop that runs thousands of times, repeated allocation can add up. The time complexity is O(n), where n is the final string length, because the method must copy the original characters and then write the padding.
If you are building a large block of aligned text, consider constructing the entire output in a list and joining it once, rather than repeatedly concatenating padded strings. Concatenation in a loop creates intermediate strings and can be slower.
# Avoid this in a tight loop: result = "" for item in items: result += item.ljust(20) + "\n" # Prefer building a list and joining: lines = [item.ljust(20) for item in items] result = "\n".join(lines)
The list comprehension still creates padded strings, but it avoids the quadratic behavior of repeated += on a growing string.
Common Pitfalls and Edge Cases
One subtle issue is that ljust() counts characters, not display width. In monospaced console output this is fine, but in a proportional font or with wide Unicode characters (like CJK ideographs or emoji), the visual width may not match the character count. If you need to align text containing such characters, you must account for their display width separately.
Another pitfall is passing a non-integer width. The method expects an integer; passing a float raises a TypeError. Also, width can be negative; in that case the method behaves as if width were 0 and returns the original string unchanged.
print("abc".ljust(-5)) # "abc"
Finally, remember that ljust() returns a new string. If you ignore the return value, the original string remains unchanged, which can lead to bugs if you expect in-place modification.
name = "Ada" name.ljust(10) # result is discarded print(name) # still "Ada"
Understanding these edge cases helps you use ljust() reliably in production code, especially when generating reports or user-facing output where alignment matters.