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

Python basic tutorial

Python flow control

Função do Python

Tipos de Dados do Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python string ljust() usage and examples

Python string methods

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

The return value of the string ljust()

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.

Example1Minimum width of the left-aligned string

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

Example2Left-aligned 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 the character "

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

Python string methods