Python String ljust() Method
The ljust()
method returns a left-justified version of the original string, padded with a specified character (default is space) to reach a specified width.
Syntax
string.ljust(width, fillchar)
Parameters
width
(required): The total length of the returned string after padding. If the specified width is less than or equal to the length of the string, the original string is returned.
fillchar
(optional): The character to use for padding. The default is space.
Return Value
Returns a new string that is left-justified with the specified fill character padding it to the right.
Examples
Left Justify a String
text = "mango"
result = text.ljust(10)
print(f"{result}is love") # Output: mango is love
In this example, "mango"
has 5
characters.
text.ljust(10)
pads it with 5 spaces on the right, so it becomes:
`"mango "
Using a Custom Fill Character
text = "mango"
result = text.ljust(10, "-")
print(result) # Output: mango-----
print(f"{result}is love") # Output: mango-----is love
When Width is Less Than String Length
If the specified width is less than or equal to the length of the original string, the original string is returned without any changes.
text = "mango"
result = text.ljust(3, "-")
print(result) # Output: mango
If you need to right-justify the string, you can use the rjust()
method.