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
- 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
- Basic usage with default padding (spaces):
- Using a custom fill character:
- 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:
- Padding with a different fill character:
You can specify any single character for padding:
- Empty string:
If an empty string is passed, the result will also be an empty string regardless of the specified width:
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.