Home >Backend Development >Python Tutorial >How to Pad Strings with Spaces in Python?
Padding Strings with Spaces in Python
When it comes to filling out strings with spaces, Python provides a convenient and concise solution. While zero-padding is achievable using the d string formatting option, the task of adding spaces calls for a different approach.
To fill out a string with spaces, the str.ljust(width[, fillchar]) method is the go-to tool. This method left-justifies the input string within a specified width, using the provided fill character (a space by default). Here's how it works:
>>> 'hi'.ljust(10) 'hi '
In this example, the string 'hi' is left-justified within a string of length 10, resulting in 'hi ' with eight trailing spaces. The fillchar argument can be modified to use a character of your choice for padding.
The above is the detailed content of How to Pad Strings with Spaces in Python?. For more information, please follow other related articles on the PHP Chinese website!