The Python ljust() function allows us to left justify string variables.
string = "hello"
print(string.ljust(8))
#Output:
hello
You can also pass a second parameter which will be used to fill the blank spaces created by ljust().
string = "hello"
print(string.ljust(8, "x"))
#Output:
helloxxx
When working with strings, the ability to easily modify the values of the variables easily is valuable.
One such situation where you might want to make a change to a string is if you want to left justify a string variable.
The Python ljust() function allows us to left justify string variables.
ljust() takes two parameters. The first is the length of the new string that ljust() will create and the second parameter is a fill character to add to the right of the string.
Below is a simple example showing you how to use ljust() to return a left justified string in Python.
string = "hello"
print(string.ljust(8))
#Output:
hello
Using the Fill Parameter with ljust() Function
The second parameter allows you to fill the blank space with a given character. This can be useful if you want to add trailing characters to a string.
Below is a simple example showing you how to return a left justified string with ljust() and fill the blank spaces with a character in Python.
string = "hello"
print(string.ljust(8, "x"))
#Output:
helloxxx
Using ljust() Function to Add Trailing Zeros to String in Python
One useful example of ljust() is that you can add trailing zeros to a string in Python is with the ljust() function.
Adding trailing zeros with ljust() is useful if you want to get a specific length for your new string and don’t always know the length of the string variable you are using.
Below is an example of adding trailing zeros to a string with ljust() in Python.
string = "hello"
print(string.ljust(8,"0"))
#Output:
hello000
Right Justifying String Variable with Python rjust() Function
Instead of left justifying a string, if you want to right justify a string, you can use the Python rjust() function.
Just like ljust(), rjust() takes two parameters. The first is the length of the new string that rjust() will create and the second parameter is the character to add to the left of the string.
Below is a simple example showing you how to use rjust() in Python.
string = "hello"
print(string.rjust(8))
#Output:
hello
Hopefully this article has been useful for you to learn how to use the Python ljust() function.