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

Tutoriel de base Python

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python string rjust() usage and example

Python string methods

The rjust() method of the Python string returns a new string that is right-aligned from the original string, and is filled with spaces to the length width. If the specified length is less than the length of the string, it returns the original string.

The syntax of the rjust() method is:

string.rjust(width[, fillchar])

fillchar is an optional parameter.

String rjust() parameters

The rjust() method takes two parameters:

  • width-The width of the given string. If width is less than or equal to the length of the string, return the original string.

  • fillchar (optional) -Character used to fill the remaining space of the fill width

From the rjust() return value of the string

The rjust() method returns a right-aligned string within the given minimum width...

If fillchar is defined, use the defined character to fill the remaining space.

Example1:Right-align the string with the minimum width

# Example string
string = 'cat'
width = 5
# Print right-aligned string
print(string.rjust(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.

Now, rjust() aligns the string 'cat' to the right, leaving two spaces on the left of the word.

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

# Example string
string = 'cat'
width = 5
fillchar = '*'
# Print right-aligned string
print(string.rjust(width, fillchar))

When running the program, the output is:

**cat

Here, the string “cat” is right-aligned, and the remaining two spaces on the left are filled with fillchar “ *” Padding.

Note:If you want to align the string to the right, please useljust()You can also useformat()Formatted strings.

Python string methods