Home >Backend Development >Python Tutorial >How Can I Left-Pad a String or Number with Zeros in Python?

How Can I Left-Pad a String or Number with Zeros in Python?

Linda Hamilton
Linda HamiltonOriginal
2025-01-01 07:26:10634browse

How Can I Left-Pad a String or Number with Zeros in Python?

Pad Strings with Zeros

This article addresses the query of how to add zero padding to the left of a numerical string, ensuring a specific length for the string. Two primary methods exist for achieving this: padding strings and padding numbers.

Padding Strings

To pad strings, use the zfill() function:

n = '4'
print(n.zfill(3))  # Outputs "004"

Padding Numbers

For numbers, there are several options:

  • f-strings (Python ≥3.6):
n = 4
print(f'{n:03}')  # Recommended, Outputs "004"
  • % formatting (Python 2.6 ):
print('%03d' % n)  # Outputs "004"
  • format() function (Python 2.6 ):
print(format(n, '03'))  # Outputs "004"
print('{0:03d}'.format(n))  # Outputs "004"
print('{foo:03d}'.format(foo=n))  # Outputs "004"
  • format() with curly brackets (Python 2.7 ):
print('{:03d}'.format(n))  # Outputs "004"

Refer to the official String formatting documentation for further information.

The above is the detailed content of How Can I Left-Pad a String or Number 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