The rjust
method will return a right-justified string of length as width by adding a specified fill character to the beginning of the string.
str.rjust(width, fillchar)
width
: The resulting string length.
fillchar
: The character to be added at the start of the string. It is an optional value. By default, the space will be added. This parameter is optional.
If the width
is greater than the length of the string, then the specified filchar
will be added at the beginning of the string to make the string length equal to the passed width
value.
If the width
is less than the length of the string, then the original string is returned.
string = "123"print(string.rjust(4))print(string.rjust(5, '*'))print(string.rjust(10, '#'))print(string.rjust(1, '#'))
In the code above, we created a string, 123
. Then:
Called the rjust
method with width
as 4
. In this case, the string length is 3
and the width is 4
. 4
is greater than 3
and their difference is one, so one space
(default fillchar
) is added to the beginning of the string, and " 123"
is returned.
Called the rjust
method with width
as 5
and fillchar
as *
. In this case, the string length is 3
and the width is 5
. 5
is greater than 3
and their difference is two, so two *
are added to the beginning
of the string and **123
is returned.
Called the rjust
method with width
as 10
and fillchar
as #
. In this case, the string length is 3
and the width is 10
. 10
is greater than 3
and their difference is seven, so seven #
are added to the beginning of the string and #######123
is returned.
Called the rjust
method with width
as 1
and fillchar
as #
. In this case, the string length is 3
and the width is 1
. 1
is smaller than 3
, so the string and 123
will be returned.