Python String ljust() method
Python String ljust() method
The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default).
Syntax
String.ljust(width[, fillchar])
Parameter
width: This parameter represents the length of the returned string.
fillchar(Optional): This parameter represents a character to fill the missing space (to the right of the string). Default is " " (space).
Return
This method returns the string left a justified string of the given width. The original string is returned if the width is less than the length of the String.
Example 1
# Python program explaining # the string.ljust() method # initializing the string string = "Python" # initializing the length width=21 # string with " " padding val = string.ljust(width) # default padding value is " " # printing the left aligned string print(val, "is my favorite programming language.")
Output
Python is my favorite programming language.
Example 2
# Python program explaining # the string.ljust() method # initializing the string string = "Hello World" # Printing the actual string print ("The actual string:", string, "\n") # Printing the left aligned # string with "!" padding print ("The left aligned string:", string.ljust(40, '!'))
Output
The actual string: Hello World The left aligned string: Hello World!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Example 3
# Python program explaining # the string.ljust() method # initializing the string string = "Morning" # Printing the actual string print ("The actual string:", string, "\n") # Printing the left aligned # string with "*" padding print ("The left 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 left aligned string with width 2:", string.ljust(2, '*'))
Output
The actual string: Morning The left aligned string with width 40: Morning********************************* The left aligned string with width 2: Morning