What is a string.rjust() in Python?
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.
Syntax
str.rjust(width, fillchar)
Parameters
-
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.
Return value
-
If the
widthis greater than the length of the string, then the specifiedfilcharwill be added at the beginning of the string to make the string length equal to the passedwidthvalue. -
If the
widthis less than the length of the string, then the original string is returned.
Code
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
rjustmethod withwidthas4. In this case, the string length is3and the width is4.4is greater than3and their difference is one, so onespace(defaultfillchar) is added to the beginning of the string, and" 123"is returned. -
Called the
rjustmethod withwidthas5andfillcharas*. In this case, the string length is3and the width is5.5is greater than3and their difference is two, so two*are added to the beginning of the string and**123is returned. -
Called the
rjustmethod withwidthas10andfillcharas#. In this case, the string length is3and the width is10.10is greater than3and their difference is seven, so seven#are added to the beginning of the string and#######123is returned. -
Called the
rjustmethod withwidthas1andfillcharas#. In this case, the string length is3and the width is1.1is smaller than3, so the string and123will be returned.