The Wayback Machine - https://web.archive.org/web/20240205202948/https://www.geeksforgeeks.org/string-rjust-ljust-python/
Open In App
Related Articles

String rjust() and ljust() in python()

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

1. String rjust() The string rjust() method returns a new string of given length after substituting a given character in left side of original string.

Syntax:

string.rjust(length, fillchar)

Parameters:

length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.
fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument.

Returns:

Returns a new string of given length after substituting a given character in left side of original string.

Example




# Python program to demonstrate working of 
# rjust()
string = 'geeks'
length = 8
  
# If no fill character is provided, space
# is used as fill character
print(string.rjust(length))


Output:

   geeks

Example




# example string
string = 'geeks'
length = 8
fillchar = '*'
  
print(string.rjust(length, fillchar))


Output:

***geeks  

 

2. String ljust()
The string ljust() method returns a new string of given length after substituting a given character in right side of original string.

Syntax:

string.ljust(length, fillchar)

Parameters:

length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.
fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument.

Returns:

Returns a new string of given length after substituting a given character in right side of original string.

Example 1




# example string
string = 'geeks'
length = 8
  
# If no fill character is provided, space
# is used as fill character.
print(string.ljust(length))


Output: (Three spaces are printed after geeks)

geeks   

Example 2




# example string
string = 'geeks'
length = 8
fillchar = '*'
  
# print left justified string
print(string.ljust(length, fillchar))


Output:

geeks***  

Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.


Last Updated : 08 Jan, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials