English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operation

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python string ljust() usage and example

Python string methods

The ljust() method of string in Python 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.

String ljust() parameters

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) -Character used to fill the remaining space of the fill width

String ljust() return value

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.

Example1:Left-aligned string with minimum width

#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.

Example2:Left-align the string and fill the remaining spaces

#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 quotes.

Note:If you want to right-align a string, please userjust()You can also useformat()Method to format strings.

Python string methods