Home >Backend Development >Python Tutorial >How Can I Pad a Python String with Spaces?
Pad a Python String with Spaces
In Python, you may encounter the need to fill out a string with spaces. While using d%4 can be effective for zero-padding, it's not applicable for space-padding. To achieve this, a more versatile approach is required.
Solution:
To fill out a string with spaces in Python, you can leverage the str.ljust(width[, fillchar]) method. It returns the string left-justified in a string of a specified width, using a specific fillchar (defaulting to space). If the original string length (len(s)) exceeds the width, the original string is returned unchanged.
Usage:
>>> 'hi'.ljust(10) 'hi '
In the example above, the str.ljust() method pads the string 'hi' with spaces to achieve a total width of 10 characters. This results in the output 'hi ', as desired.
This method provides a concise and flexible way to fill out strings with spaces or any other desired character.
The above is the detailed content of How Can I Pad a Python String with Spaces?. For more information, please follow other related articles on the PHP Chinese website!