When working with strings in Python, it can be useful to add spaces to them for alignment or formatting purposes. While padding with zeros is straightforward using the % operator, achieving the same effect with spaces requires a different approach.
To fill a string with spaces in Python, you can use the str.ljust(width[, fillchar]) method. This method returns a new string that is left-justified within a string of a specified width, using the optional fillchar (which defaults to a space) for padding.
For example, to add spaces to the left of the string 'hi' to create a 10-character-wide string, you can use the following code:
hi.ljust(10)
This will output the string 'hi ' with eight spaces added to the left of the original string.
The str.ljust() method offers several advantages over other approaches:
Here are some additional examples of using str.ljust() to fill strings with spaces:
# Center a string within a 20-character-wide string "Hello".ljust(20, ".") # Truncate a string to a maximum width of 10 characters "Lorem ipsum".ljust(10, ".") # Use spaces as the fill character to right-justify a string "Goodbye".ljust(15)
The above is the detailed content of How Can I Easily Pad a Python String with Spaces?. For more information, please follow other related articles on the PHP Chinese website!