Home >Backend Development >Python Tutorial >How Can I Efficiently Pad a Python String with Spaces?
When working with strings, you may encounter scenarios where you need to pad a string with a specific number of spaces. While you can manually calculate the spaces and concatenate them to the string, a more efficient approach is available in Python.
To fill out a string with spaces, you can utilize the str.ljust() method, which left-justifies a string within a specified width. It has the following syntax:
str.ljust(width[, fillchar])
For instance, if you want to pad the string "hi" with 10 spaces, you can use the following code:
'hi'.ljust(10)
This will return the string "hi " padded with 10 spaces.
You can specify a custom fill character instead of the default space. For example, to pad the string "hello" with 5 underscores:
'hello'.ljust(10, '_')
This will result in "hello____", where the missing spaces are replaced with underscores.
The above is the detailed content of How Can I Efficiently Pad a Python String with Spaces?. For more information, please follow other related articles on the PHP Chinese website!