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
Release: 2025-01-01 07:26:10
Original
577 people have browsed it

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

Padding Numbers

For numbers, there are several options:

  • f-strings (Python ≥3.6):
n = 4
print(f'{n:03}')  # Recommended, Outputs "004"
Copy after login
  • % formatting (Python 2.6 ):
print('%03d' % n)  # Outputs "004"
Copy after login
  • 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"
Copy after login
  • format() with curly brackets (Python 2.7 ):
print('{:03d}'.format(n))  # Outputs "004"
Copy after login

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!

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