Python String ljust()
Method
The ljust() method in Python left-aligns a string by padding it with spaces (or a specified character) until it reaches the desired width.
Syntax
string.ljust(width, fillchar=' ')
Parameters:
width
– Total length of the resulting string (including the original string and padding)fillchar
(optional) – The character to use for padding. Default is a space' '
Returns:
- A new string that is left-justified and padded to the specified width.
Example 1: Left-justify with spaces (default)
text = "Hello"
print(text.ljust(10))
Hello
Explanation: The word "Hello"
is padded with 5 spaces on the right to make the total length 10.
Example 2: Left-justify with a custom character
text = "Hi"
print(text.ljust(6, '-'))
Hi----
Explanation: The string "Hi"
is padded with 4 hyphens '-'
on the right.
Use Cases
- Formatting tabular text output
- Aligning labels or values in console applications
- Creating fixed-width string formats
Common Mistakes
fillchar
must be a single character. Using more than one character will raise an error.- If
width
is less than or equal to the string's length, the original string is returned unchanged.
Interview Tip
Use ljust()
in string formatting questions where consistent alignment of text output is required.
Summary
ljust()
pads the string on the right to make it left-aligned.- It returns a new string with the specified total width.
- Great for creating aligned outputs and formatted strings.
Practice Problem
Write a Python program that prints a list of names left-aligned within 15 characters using ljust()
.
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name.ljust(15) + "|")
Expected Output:
Alice |
Bob |
Charlie |