Python string rfind() method with example

The rjust() method in Python is used to right-justify a string within a specified width. It’s often used to format text output in a way that aligns content to the right, typically when you want to create neatly formatted columns of text or numbers.

Here’s the syntax for the rjust() method:

str.rjust(width[, fillchar])

width is the total width of the resulting string, which includes the original string itself. If the original string is already as wide or wider than the specified width, no changes are made.

fillchar (optional) is the character used for padding. It’s usually a space character by default, but you can specify a different character if needed.

Here’s an example of how to use rjust():

text = "Hello"
right_justified = text.rjust(10)
print(right_justified)

In this example, the string “Hello” is right-justified within a total width of 10 characters, so it adds spaces on the left to achieve this width. The output would be:

   Hello

You can also specify a fillchar if you want to use a different character for padding:

text = "Hi"
right_justified = text.rjust(10, '-')
print(right_justified)

In this case, it will use hyphens for padding:

--------Hi

Example 1

Creating a Right-Aligned Table of Data.

data = [
  ["Alice", 28, 175],
  ["Bob", 32, 180],
  ["Charlie", 24, 170]
]

for row in data:
  name, age, height = row
  print(f"{name.rjust(10)} {str(age).rjust(5)} {str(height).rjust(5)}")

Example 2

Formatting Numeric Output.

price = 19.99
discount = 5.00
total = price - discount

print(f"Price: ${price:.2f}")
print(f"Discount: ${discount:.2f}")
print(f"Total: ${total:.2f}".rjust(20))

Example 3

Numbered List with Right-Aligned Numbers.

items = ["Apples", "Bananas", "Cherries", "Dates"]
for i, item in enumerate(items, start=1):
  print(f"{str(i).rjust(2)}. {item}")