Python String ljust() Method
Last Updated : 02 Jan, 2025
Improve
Python ljust() method is used to left-justify a string, padding it with a specified character (space by default) to reach a desired width. This method is particularly useful when we want to align text in a consistent format, such as in tables or formatted outputs.
Here's a basic example of how to use ljust() method:
s1 = "Hello"
s2 = s1.ljust(10)
print(s2)
Output
Hello
Explanation:
- In this example, the string "Hello" is left-justified to a width of 10 characters, with spaces added to the right.
Table of Content
Syntax of ljust() method
string.ljust(width, fillchar=' ')
Parameters:
- width: The total width of the resulting string. If the original string is shorter than this width, it will be padded with the fillchar.
- fillchar (optional): The character to use for padding. The default is a space.
Return Type:
- Returns a new string of given length after substituting a given character in right side of original string.
Using the default fill character
The ljust()
method can be used without specifying a fillchar
, in which case it defaults to a space.
s = "Python"
# Left-aligning the string with a total width of 12
res = s.ljust(12)
print(res)
Output
Python
Explanation:
- The string
s
is left-aligned in a field of width 12. - The remaining space is filled with spaces.
Specifying a custom fill character
Sometimes, we may want to use a character other than a space to fill the remaining space. The ljust()
method allows you to specify a custom fillchar
.
s = "Data"
# Left-aligning the string with
# a width of 10 and using '-' as the fill character
res = s.ljust(10, '-')
print(res)
Output
Data------
Explanation:
- The
fillchar
parameter is set to'-'
, so the remaining space is filled with dashes. - This can be useful for creating custom formatting styles.
Combining ljust()
with other string methods
ljust()
method can also be used alongside other string methods to achieve more complex formatting.
s = "Align"
# Left-aligning the string and converting it to uppercase
res = s.ljust(10).upper()
print(res)
Output
ALIGN
Explanation:
- The string
s
is left-aligned in a field of width 10. - The resulting string is then converted to uppercase using the
.upper()
method.