Home >Backend Development >Python Tutorial >How Can I Add Leading Zeros to Numeric Strings in Python?

How Can I Add Leading Zeros to Numeric Strings in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 14:24:10424browse

How Can I Add Leading Zeros to Numeric Strings in Python?

Zero-Padding Numeric Strings

To add leading zeros to a numeric string, enhancing its length, multiple approaches can be employed in Python:

Padding Strings:

For string padding, the zfill method is utilized:

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

Padding Numbers:

Various methods can be used to pad numbers:

  • f-Strings (Preferred for Python >= 3.6):
n = 4
print(f'{n:03}')  # Output: 004
  • Modulo Operator:
print('%03d' % n)  # Output: 004
  • format Function (Python >= 2.6):
print(format(n, '03'))  # Output: 004
print('{0:03d}'.format(n))  # Output: 004
print('{foo:03d}'.format(foo=n))  # Output: 004
  • format_spec Mini-Language (Python >= 2.7 Python 3):
print('{:03d}'.format(n))  # Output: 004

Consult the String Formatting documentation for further details.

The above is the detailed content of How Can I Add Leading Zeros to Numeric Strings 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