ljust() makes a string at least width characters long by adding padding on the right, so the text stays at the left. "hi".ljust(5) is "hi ", which is the text plus three spaces.
The padding is made of spaces unless you pass a one-character fillchar. If the string is already as long as width, or longer, it is returned as it is: ljust() never cuts text. The method returns a new string.
text.ljust() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Pass the total width. The fill character is optional.
Returns 'hi '. Three spaces are added on the right.
"hi".ljust(5, ".")
Returns 'hi...'. The padding is made of dots.
"python".ljust(3)
Returns 'python'. The text is already longer than the width, so it is unchanged.
To pad on the left use rjust(), to centre the text use center(), and to pad a number with zeros use zfill().
Library declarations
python
str.ljust(width[, fillchar]) -> str
# returns: a new string at least width characters long
# raises: TypeError if fillchar is not exactly one character
Parameters
Parameter
Description
width
Required. The length of the final string. If it is not larger than the length of the text, nothing is added.
fillchar
Optional. The character used for padding. It must be a string of exactly one character. Default is a space.
Return Value
Return Value
Description
str
A new string of length max(width, len(text)), with the text at the left. The original string is not changed.
Python Examples
Example 1 — Left-Align Text in a Field
Pad a name to 8 characters, with spaces and with dots, and try a width that is too small.