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

How Can I Pad a Python String with Spaces?

Mary-Kate Olsen
Release: 2024-12-10 17:16:13
Original
466 people have browsed it

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

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!

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