Home >Backend Development >Python Tutorial >How Can I Efficiently Pad a Python String with Spaces?

How Can I Efficiently Pad a Python String with Spaces?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 01:44:14318browse

How Can I Efficiently Pad a Python String with Spaces?

Filling 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.

Solution: Utilizing str.ljust()

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])
  • width: The desired width of the padded string.
  • fillchar: An optional character (defaults to space) used for padding.

Example

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.

Custom Fill Character

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn