How to Right-align in Python

In this tutorial, we’ll delve into how you can right-align text or other kinds of data in Python. Right alignment of information can be incredibly useful in a variety of cases, such as when aligning data in tables for visibility or while creating custom text layouts. So, it’s a nice trick to have up your sleeve as a Python coder.

Getting started with basic right-alignment

Python has a built-in method for right-alignment, the str.rjust() method. This method will align the text to the right side of the string with a specified width. Take the following simple example:

The str.rjust() method will pad the left side of the string with spaces until the string’s width is 10 characters.

Right-aligning with Filling Characters

If you want to fill the empty spaces with a character other than the space character, you can provide that character as a second argument to the rjust() method. Here’s how you do that:

This will pad the string with ‘-‘ characters on the left until the string’s width is 10 characters.

Right alignment using the Format method

Another way to accomplish the right alignment in Python is by using the format() method. Using this method, we can control the alignment of text by specifying a character for alignment:

Here, ‘>10’ specifies right alignment and a total width of 10 characters.

Complete Python Code

Here are all the examples in one place:

| Python tutorial |
| ----Python |
|    Python|

Conclusion

That sums up the basics of right alignment in Python. Whether you’re formatting tables for a data science project, or simply creating pretty printed text, the right alignment is an essential tool in your Python toolkit.

Learning to code in Python opens up a multitude of opportunities, and understanding the available methods and formatting options will surely help in your coding journey. Happy coding!