Home >Backend Development >Python Tutorial >How to Pad Strings and Numbers with Zeros in Python?

How to Pad Strings and Numbers with Zeros in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 17:48:10819browse

How to Pad Strings and Numbers with Zeros in Python?

Padding Strings with Zeros

In Python, strings and numbers can be padded with zeros to a specific length. Here's how to achieve this:

Padding Strings

To pad a string with zeros, use the zfill() method. For example:

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

This will pad the string with zeros until it reaches the specified length.

Padding Numbers

Numbers can be padded with zeros using various methods:

  • Formatted String Literals (f-strings):
n = 4
print(f'{n:03}')  # Output: 004
  • Formatted String Operator:
n = 4
print('%03d' % n)  # Output: 004
  • String Format Method:
n = 4
print(format(n, '03'))  # Output: 004
  • Named Formatted Strings:
n = 4
print('{0:03d}'.format(n))  # Output: 004
  • Keyword Formatted Strings:
n = 4
print('{foo:03d}'.format(foo=n))  # Output: 004
  • String Interpolation:
n = 4
print('{:03d}'.format(n))  # Output: 004

For more information on string formatting, refer to the official Python documentation.

The above is the detailed content of How to Pad Strings and Numbers with Zeros in Python?. 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