Home > Backend Development > Python Tutorial > How to Pad Strings with Spaces in Python?

How to Pad Strings with Spaces in Python?

Patricia Arquette
Release: 2024-12-09 05:33:12
Original
317 people have browsed it

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        '
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template