Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is ljust() in Python?

Mahnoor Zaheer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The ljust() method in Python is a string function that returns a left-justified string with a length equal to the specified width.

Syntax

The syntax of this function is as follows:

string.ljust(width, char)

Parameters and Return value

The ljust() method takes two parameters, which are described below:

  1. width (required): This argument defines the total length of the string that is required. If it is smaller or equal to the current length of the string, the function returns the same string.
  2. char (optional): It is the character that is added to the string to increase its length according to the specified width. If this is not specified, empty spaces are added to the string.

The return value is a copy of the string with extended length.

Code

In the code below, when no fill character is specified, ljust() is adding empty spaces to string ‘hello’ and extends its length to 7. Consequently, if the character ‘/’ is defined in the function, it adds ‘/’ to extend the length of the string to the specified value ljust().

# example string
string = 'hello'
# without any fill character, adding empty spaces
x = string.ljust(7)
print(x , 'with length', len(x))
# with fill character, adding '/'
y = string.ljust(7, '/')
print(y , 'with length', len(y))
The syntax of ljust() method in Python

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring