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

How Can I Pad Strings with Spaces in Python?

Barbara Streisand
Release: 2024-12-04 11:51:11
Original
452 people have browsed it

How Can I Pad Strings with Spaces in Python?

Padding Strings with Spaces in Python

While the "d" format string can be used to pad a string with zeros, a more general way to pad a string with any character is required. This is where the str.ljust(width[, fillchar]) method comes into play.

How it Works

The str.ljust() method returns a copy of the string left-justified in a string of length width. If width is less than the length of the string, no padding is applied. Otherwise, the string is padded with the specified fillchar character (default is a space).

Example

Consider the following example:

>>> 'hi'.ljust(10)
'hi        '
Copy after login

In this example, the string 'hi' is padded with spaces to a total width of 10. Note the 8 spaces that were added to the end of the original string.

Conclusion

The str.ljust() method is a versatile tool for padding strings with spaces or any other desired character. It provides a concise and efficient solution compared to manually measuring string lengths and concatenating spaces.

The above is the detailed content of How Can I 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