English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The string ljust() method returns a new string that is left-aligned from the original string and filled with spaces to the specified length.
The syntax of the ljust() method is:
string.ljust(width[, fillchar])
fillchar is an optional parameter.
The ljust() method takes two parameters:
width-The width of the given string. If the fill width is less than or equal to the length of the string, the original string is returned.
fillchar (optional) -The character used to fill the remaining space of the fill width
The ljust() method returns a left-aligned string within the given minimum width.
If fillchar is defined, the remaining space will also be filled with the defined character.
# String string = 'cat' width = 5 # Print left-aligned string print(string.ljust(width))
When running the program, the output is:
cat
Here, the minimum value defined by width is5. Therefore, the minimum length of the resulting string is5.
And, the string "cat" is left-aligned, leaving two spaces on the right of the word.
# Example string string = 'cat' width = 5 fillchar = '*' # Print left-aligned string print(string.ljust(width, fillchar))
When running the program, the output is:
cat**
Here, the string "cat" is left-aligned, and the remaining two spaces on the right are filled with the character" *Fill with the character "
Note:If you want to right-align the string, please userjust()You can also useformat()Method to format strings.