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
Release: 2024-12-27 14:24:10
Original
455 people have browsed it

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

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
Copy after login
  • Modulo Operator:
print('%03d' % n)  # Output: 004
Copy after login
  • 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
Copy after login
  • format_spec Mini-Language (Python >= 2.7 Python 3):
print('{:03d}'.format(n))  # Output: 004
Copy after login

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!

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