Home > Backend Development > Python Tutorial > How Can I Pad Strings and Numbers with Leading Zeros in Python?

How Can I Pad Strings and Numbers with Leading Zeros in Python?

Susan Sarandon
Release: 2024-12-20 08:39:10
Original
467 people have browsed it

How Can I Pad Strings and Numbers with Leading Zeros in Python?

String Padding with Zeros

Adding zeros to the left of a string to reach a specific length is a common task in programming. This technique is useful for formatting numeric values, ensuring consistent field widths, and other applications.

String Padding

To pad strings with zeros, Python provides the zfill() method. For instance, if we have a string n = '4', we can pad it to a length of 3 zeros as follows:

n = '4'
print(n.zfill(3))  # Output: 004
Copy after login

Number Padding

Padding numbers is similar to padding strings. However, Python offers several methods to achieve this. One preferred method, available in Python 3.6 and later, is using the f-string syntax:

n = 4
print(f'{n:03}')  # Output: 004
Copy after login

Alternatively, you can use the % operator:

print('%03d' % n)  # Output: 004
Copy after login

Or the format() function:

print(format(n, '03'))  # Output: 004
print('{0:03d}'.format(n))  # Output: 004
Copy after login

For advanced use cases, you can specify additional parameters within the formatting string to control various aspects of the padding. Refer to the String Formatting documentation for more information.

The above is the detailed content of How Can I Pad Strings and Numbers with Leading Zeros 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