Python string rjust() method with example

In Python, the rjust() method is a built-in method that is used to right-justify a string within a specified width. It returns a new string that is left-padded with a specified character (by default, it pads with spaces) to reach the desired width.

The basic syntax for the rjust() method is as follows:

str.rjust(width[, fillchar])

str is the string that you want to right-justify.

width is the total width of the resulting string, including the original string and any padding characters.

fillchar (optional) is the character used for padding. If not provided, it defaults to a space.

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

text = "Hello"
justified_text = text.rjust(10, "-")
print(justified_text)

Output:

-----Hello

Example 1

You can use rjust() to align text in columns when displaying tabular data, making it easier to read.

data = [["Alice", 25], ["Bob", 30], ["Carol", 22]]
for item in data:
  name, age = item
  print(f"{name.rjust(10)} | {str(age).rjust(3)}")

Output:

  Alice | 25
   Bob | 30
  Carol | 22

Example 2

Right-aligning numbers is useful when working with numeric data.

number = 42
right_aligned = str(number).rjust(5, "0")
print(right_aligned)

Output:

00042

Example 3

You can use a customized padding character, like an underscore, instead of spaces.

text = "Python"
justified_text = text.rjust(10, "_")
print(justified_text)

Output:

______Python

Leave a Reply

Your email address will not be published. Required fields are marked *