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
1 2 3 |
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
1 2 3 4 5 6 7 8 9 10 11 12 |
# 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
1 2 3 |
Python is my favorite programming language. |
Example 2
1 2 3 4 5 6 7 8 9 10 11 |
# 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
1 2 3 4 |
The actual string: Hello World The left aligned string: Hello World!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |
Example 3
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 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
1 2 3 4 5 |
The actual string: Morning The left aligned string with width 40: Morning********************************* The left aligned string with width 2: Morning |