lettura simple

The rjust() Method in Python

In Python, the rjust() method is a handy tool for handling string alignment. Specifically, it enables you to align a string to the right and fill the left side with a character of your choice until it reaches a certain length. Here's how it looks in action:

string.rjust(length[, fill])

Here, 'string' is the object - the string we're aligning to the right.

This method accepts two parameters:

  • The desired length of the string after processing.
  • An optional fill character, which you can use to pad the string from the left until it hits the designated length.

What you get as a result is a fresh string, right-aligned and leading with a series of fill characters on the left, all up to your specified length.

Remember, the fill character isn't limited to a single character - it could also be a sequence. If you don't specify a fill character, the method will simply use a blank space as the default.

Let's look at a concrete example.

Firstly, assign a string to a variable, let's call it "text".

>>> text = "Hello"

Next, use the rjust() method to generate a 10-character string.

We'll right-align the original string and use the asterisk "*" as the fill character.

>>> text.rjust(10, "*")

The outcome? A brand-new 10-character string. Our original "Hello" is neatly right-aligned, with a sequence of "*" filling out the left.

*****Hello

This technique is a neat way to format a string to a predefined length, filling any leftover space on the left with a character that suits your needs.

One key point to remember is that rjust() doesn't alter the original string value. Instead, it creates a new string.

But what if the initial string is already longer than the length you've specified?

In that case, rjust() simply returns the original string in its entirety, without any truncation

For example, if we type text.rjust(3, "*")

>>> text.rjust(3, "*")

Here, the string "Hello" is 5 characters long - longer than the specified length of 3.

As a result, rjust() gives us back the original string, "Hello", completely intact.

Hello




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin