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

Python Basic Tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python string rjust() usage and example

Python string methods

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

The syntax of the rjust() method is:

string.rjust(width[, fillchar])

fillchar is an optional parameter.

String rjust() parameter

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

From the return value of the string rjust()

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" *Filling.

Note:If you want to right-align a string, please useljust()You can also useformat()String formatting.

Python string methods