Header Graphic
Member's Message > Understanding str.rjust() in Python: A Guide to Ri
Understanding str.rjust() in Python: A Guide to Ri
Login  |  Register
Page: 1

rashmi agar
67 posts
Mar 17, 2025
10:05 PM
Python provides a variety of built-in string manipulation methods, and one such useful method is str.rjust . This method allows you to right-align a string within a specified width by padding it with a given character. It is particularly useful when formatting text for output, such as tables or reports.

What is str.rjust()?
The str.rjust() method returns a right-aligned string of a specified width by padding it with a specified character (default is a space). The syntax is:

python
Copy
Edit
str.rjust(width, fillchar)
width: The total width of the resulting string.
fillchar (optional): The character used for padding (default is a space).
Examples of str.rjust()
Example 1: Basic Right-Alignment
python
Copy
Edit
text = "Python"
aligned_text = text.rjust(10)
print(aligned_text) # Output: " Python"
In this example, the string "Python" is right-aligned within a width of 10, filling the extra spaces on the left with spaces.

Example 2: Using a Custom Fill Character
python
Copy
Edit
text = "Python"
aligned_text = text.rjust(10, '-')
print(aligned_text) # Output: "----Python"
Here, the fill character is set to '-', which pads the string instead of spaces.

Use Cases of str.rjust()
Formatting Tabular Data:
When displaying text-based tables in the console, rjust() helps align columns neatly.

python
Copy
Edit
headers = ["Name", "Age", "Score"]
data = [
["Alice", 23, 85],
["Bob", 30, 92],
["Charlie", 27, 78]
]

print(headers[0].rjust(10), headers[1].rjust(5), headers[2].rjust(6))
for row in data:
print(str(row[0]).rjust(10), str(row[1]).rjust(5), str(row[2]).rjust(6))
Creating Neatly Formatted Logs:
Right-aligning text can make logs easier to read.

python
Copy
Edit
log_level = "ERROR"
message = "File not found"
print(log_level.rjust(10) + " | " + message)
Output:

arduino
Copy
Edit
ERROR | File not found
Limitations of str.rjust()
It does not modify the original string; it returns a new string.
If the specified width is smaller than the string length, it returns the original string.
Conclusion
The str.rjust() method is a simple yet powerful tool for aligning text in Python. It is particularly useful for formatting outputs, displaying tabular data, and improving readability in logging. By mastering rjust(), you can enhance the clarity and presentation of your Python programs.


Post a Message



(8192 Characters Left)


Copyright © 2011 SUNeMALL.com All rights reserved.                             Terms of Use    Privacy Policy    Returns Policy    Shipping & Payment    Contact Us    About Us   FAQ