HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I pad a string with zeros?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withhowzerospadstring

Problem

How do I pad a numeric string with zeroes to the left, so that the string has a specific length?

Solution

To pad strings:

>>> print('4'.zfill(3))
004
>>> print('-4'.zfill(3))
-04


To pad numbers:

>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n))  # python >= 2.7 + python3
004


String formatting documentation.

Code Snippets

>>> print('4'.zfill(3))
004
>>> print('-4'.zfill(3))
-04
>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n))  # python >= 2.7 + python3
004

Context

Stack Overflow Q#339007, score: 3511

Revisions (0)

No revisions yet.