Python String rjust()

Python string rjust() method is a built-in function that will right align the string using a specified character as the fill character. The default character is space if no argument is passed.

rjust() Syntax

The syntax of rjust() method is:

string.rjust(width[, fillchar])

The fillchar is an optional parameter.

rjust() Parameters

The rjust() method can take two parameters:

  • width – length of the string with fill characters. 
  • fillchar (Optional) – A character to fill the missing space (to the right of the string). Default is space.

rjust() Return value

The rjust() method returns the right-justified string using a specified fill character and given minimum width.

The original string is returned as-is if the width is less than or equal to len(s)

Example 1 : Python program to right justify a string

In the below program, the string “ItsMyCode” will be right-justified. Since the width provided is 12 and the original string is 9 characters, the rjust() method will add the default fill char(space) padding to the left to make it 12 characters.

text = "ItsMyCode"
width = 12

print("Length of original string:", len(text))

# Default space is taken for padding
output = text.rjust(width)
print(output)
print("Length of right aligned string:", len(output))

Output

Length of original string: 9
   ItsMyCode
Length of right aligned string: 12

Example 2: rjust() Method With * fillchar

The string “Python” will be left-justified and * is used as a fill char on the right side of the string.

text = "Python"
width = 12

print("Length of original string:", len(text))

# Fill character is * over here
output = text.rjust(width, "*")
print(output)
print("Length of right aligned string:", len(output))

Output

Length of original string: 6
******Python
Length of right aligned string: 12

Example 3: Returns original string if the width is less than length of string

In this example the width specified is 10 and the length of the string is 16. Hence the rjust() method returns the original string as-is without any padding characters.

text = "Python Tutorials"
width = 10

print("Length of original string:", len(text))

# returns the original string as-is
output = text.rjust(width, "*")
print(output)
print("Length of right aligned string:", len(output))

Output

Length of original string: 16
Python Tutorials
Length of right aligned string: 16
Leave a Reply

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

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
List of Python free ebooks

List of Free Python Books

Table of Contents Hide Python SuccinctlyPython Data Science HandbookThink Python 2nd EditionAutomate the Boring Stuff with PythonMaking Games with Python & PygameData Structures and Algorithms in Python Google Python Style GuideA…
View Post