Python 3 – String ljust() Method
In Python, a string is a sequence of characters, and you can manipulate it in different ways to achieve various functionality. The ljust() method is a built-in method that allows you to left-justify a string by adding spaces at the end until it reaches a specified width. It is a very useful method for formatting output and making it easy to read. In this article, we will explore the ljust() method in detail and see its usage with examples.
Syntax
string.ljust(width[, fillchar])
The ljust() method takes two parameters, width, and fillchar (optional). The width parameter specifies the total width of the string after justification, and the fillchar parameter is optional, which, if included, specifies the character to use for filling, usually a space(‘ ‘) character. If the fillchar is not included, it defaults to the space.
Return value
The ljust() method returns the original string with fillchar added to the end as needed until it reaches the specified width.
Example
Let’s take a look at an example that demonstrates the ljust() method:
text = 'Hello World'
print(text.ljust(20))
Output:
Hello World
In this example, we first create a string ‘Hello World’. Then we call the ljust() method with a width of 20. Since the length of the string is only 11 characters, the ljust() method adds nine spaces to the end of the string to make it 20 characters long.
Use case of ljust() method
The ljust() method is a very useful method when you want to format your output in a specific way. It is particularly useful when you want to align text at the left-hand side of a column. Let’s take a look at an example of this:
names = ['Alex', 'Bob', 'Cathy', 'David']
print('Names:')
for name in names:
print(name.ljust(10))
Output:
Names:
Alex
Bob
Cathy
David
In this example, we first create a list of names. Then we print out a header, ‘Names:’, followed by each name in the list using the ljust() method with a width of 10. Since the longest name is only five characters long, the ljust() method adds five spaces to the end of each name to make it 10 characters long. This formatting makes it easy to read the names and is particularly useful when presenting data in a table format.
Conclusion
The ljust() method is a useful method for formatting output and aligning text at the left-hand side of a column. It is a built-in method in Python, so you don’t need to import anything to use it. By using the ljust() method, you can make your code more readable and presentable, which is beneficial when you are working with large amounts of data.