Open In App

Python String - ljust(), rjust(), center()

Last Updated : 02 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Strings are sequences of characters that we can manipulate in many ways. Sometimes we need to align a string to the left, right, or centre within a given space. In this article, we will explore the Difference between ljust(), just() and center().

str.ljust()

ljust() method is used to align a string to the left side and fill the remaining space on the right with a specific character (or space by default).

Syntax of ljust()

string.ljust(width, fillchar)

Parameters

  • width: The total length of the string after padding.
  • fillchar: The character to pad the string with (optional, default is space).

Return Type:

  • The return type of ljust() is a new string that is left-justified with padding.

Example of ljust()

Python
s = "Burger"

 # Padding the name with dashes until length is 20
formatted_item = s.ljust(20, "-") 
print(formatted_item) 

Output
Burger--------------

str.rjust()

The rjust() method aligns the string to the right side and fills the remaining space on the left with a specific character (or space by default).

Syntax of rjust()

string.rjust(width, fillchar)

Parameters

  • width: The total length of the string after padding.
  • fillchar: The character to pad the string with (optional, default is space).

Return Type:

  • The return type of rjust() is a new string that is right-justified with padding.

Example of rjust()

Python
a = "Hello"

# Adding dashes to the left until length is 10
b = a.rjust(10, "-")  
print(b) 

Output
-----Hello

str.center()

The center() method centers the string in the middle and fills both sides with a specific character (or space by default) to achieve a given width.

Syntax of ljust()

string.center(width, fillchar)

Parameters

  • width: The total length of the string after padding.
  • fillchar: The character to pad the string with (optional, default is space).

Return Type:

  • The return type of center() is a new string that is centered with padding on both sides.

Example of center()

Python
a = "Hello"

 # Adding dashes to both sides until length is 10
b = a.center(10, "-") 
print(b)  

Output
--Hello---

Next Article

Similar Reads