
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Right Justified String in Python
In python, Right-aligning the strings with space padding is a common requirement when formatting the text-based output such as reports, logs or tabular data. This can be done by using the built-in string methods.
Let's dive into the article, to learn different ways to get a space-padded string with the original string right-justified in python.
Using python rjust() Method
The python rjust() method is used to right-align a string by padding it with a specified character on the left.
Syntax
Following is the syntax of python rjust() method ?
str.rjust(length, character)
Example
Let's look at the following example, where we are going to consider the basic usage of the rjust() method.
x = "TutorialsPoint" y = x.rjust(20) print(repr(y))
Output
The output of the above given example is:
' TutorialsPoint'
Using python format() Method
The python format() method is used to insert the variables or values into a string. It replaces the placeholders ({}) in the string with the values we provide.
We'll use a colon (:) to indicate the amount of spaces in a curly brace that need to be filled in order to provide the proper padding.
Syntax
str.format(value1, value2...)
Example
Consider the following example, where we are going to use the format() method to align the text to right.
x = "TutorialsPoint" y = "{:>25}".format(x) print(repr(y))
Output
Following is the output of the above program ?
' TutorialsPoint'
Using python f-strings
In python, f-strings are the modern and efficient way to format strings. They are created by prefixing a string with the letter f or F. Inside the stirng, expressions or variables can be placed within the curly braces {}.
The python f-stings are introduced in the python 3.6, before that we had to use the format() method.
Example
In the following example, we are going to use f-string to align the text to the right with space padding.
x = "Welcome" y = 21 z = f"{x:>{y}}" print(repr(z))
Output
If we run the above program it will generate the following output ?
' Welcome'