The rjust()
method is a built-in method in Python that returns a right-justified string of a specified width. This method is useful for formatting strings and creating aligned columns of text.
Syntax
The syntax of the rjust()
method is as follows:
string.rjust(width, fillchar=' ')
Here, string
is the string that we want to right-justify, width
is the total width of the resulting string, and fillchar
is the character used to fill any remaining space to the left of the string. The default value of fillchar
is a space.
Return Value
The rjust()
method returns a new string that is right-justified to the specified width.
Examples
Here are three different examples of how to use the rjust()
method in Python:
Example 1: Right-Justifying a String
The following example demonstrates how to use the rjust()
method to right-justify a string:
string = "hello" result = string.rjust(10) print(result)
Output:
hello
In this example, we define a string “hello” and use the rjust()
method to right-justify it to a width of 10. The resulting string is ” hello”, with 5 spaces added to the left of the string to make it 10 characters wide.
Example 2: Using a Custom Fill Character
The following example demonstrates how to use a custom fill character with the rjust()
method:
string = "hello" result = string.rjust(10, "*") print(result)
Output:
*****hello
In this example, we define a string “hello” and use the rjust()
method to right-justify it to a width of 10, with “*” as the fill character. The resulting string is “*****hello”, with 5 asterisks added to the left of the string to make it 10 characters wide.
Example 3: Formatting Columns of Text
The following example demonstrates how to use the rjust()
method to format columns of text:
names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] for i in range(len(names)): print(names[i].rjust(10) + str(ages[i]).rjust(10))
Output:
Alice 25 Bob 30 Charlie 35
In this example, we define two lists of names and ages and use the rjust()
method to right-justify each string in the “names” list to a width of 10, and each integer in the “ages” list to a width of 10. We then print out the resulting columns of text, with the names and ages aligned in columns.
Use Cases
The rjust()
method is particularly useful when working with formatted text output. It can be used in a variety of situations where you need to align text in columns or create a consistent look to your text output. Some common use cases for the rjust()
method include:
- Creating tables of data
- Formatting reports and summaries
- Outputting text in a consistent, readable format
Overall, the rjust()
method is a powerful tool for formatting text in Python, and can help make your output more professional and easier to read.