Python String rjust() method
Python String rjust() method
The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns the original string if the argument ‘width’ is less than the length of the string.
Syntax
string.rjust(width[, fillchar])
Parameter
width: This parameter represents the width of the given string. If width is less than or equal to the length of the string, original string is returned.
fillchar: This parameter represents the character to fill the remaining space of the width
Return
This method returns a right-justified string of a given minimum width if the specified width is more than the length of the string else it returns the original string.
Example 1
# Python programming explaining # the string.rjust() method # initializing the string string = "Python" # right aligning the string, using whitespaces(by default it is whitespaces) val = string.rjust(20) # printing the value print(val, "is an easy language to learn.")
Output
Python is an easy language to learn.
Example 2
# Python program explaining # the string.rjust() method # initializing the string string = "Hello World" # Printing the actual string print ("The actual string:", string, "\n") # Printing the right aligned # string with "!" padding print ("The right aligned string:", string.rjust(40, '!'))
Output
The actual string: Hello World The left aligned string: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!Hello World
Example 3
# Python program explaining # the string.rjust() method # initializing the string string = "Morning" # Printing the actual string print ("The actual string:", string, "\n") # Printing the right aligned # string with "*" padding print ("The right aligned string with width 40:", string.ljust(40, '*')) # will return the same string the width is less than the length of the string print("The right aligned string with width 2:", string.ljust(2, '*'))
Output
The actual string: Morning The right aligned string with width 40: Morning********************************* The right aligned string with width 2: Morning