Python str.rjust() function


In Python, the str.rjust() method is used to right-align a string within a specified width, padding it with a specified character (space by default) on the left side. This method is helpful for formatting strings when you want them to appear aligned to the right within a given space, which can be particularly useful in console output or creating formatted text displays.

Syntax

str.rjust(width, fillchar=' ')
  • width: The total width of the resulting string after padding. If this value is less than the length of the original string, the original string is returned unchanged.
  • fillchar (optional): The character to use for padding the string on the left side. This must be a single character. The default is a space (' ').

Example Usage

  1. Basic usage with default padding (spaces):
text = "Hello" result = text.rjust(10) print(result) # Output: " Hello"
  1. Using a custom fill character:
text = "Hello" result = text.rjust(10, '*') print(result) # Output: "*****Hello"
  1. Width less than the original string:

If the specified width is less than the length of the original string, the original string is returned unchanged:

text = "Hello, World!" result = text.rjust(5) print(result) # Output: "Hello, World!" (unchanged)
  1. Padding with a different fill character:

You can specify any single character for padding:

text = "Python" result = text.rjust(10, '-') print(result) # Output: "----Python"
  1. Empty string:

If an empty string is passed, the result will also be an empty string regardless of the specified width:

text = "" result = text.rjust(10) print(result) # Output: " " (10 spaces)

Summary

  • Use str.rjust() to right-align a string within a specified width.
  • It allows for customizable padding using a fill character, defaulting to a space if none is specified.
  • If the specified width is less than the length of the string, the original string is returned without modification.
  • This method is useful for formatting output in console applications or in any scenario where text alignment is important.