How to Pad a String With Leading Zeros in Python 3

How do I pad a string with zeroes?

To pad strings:

>>> n = '4'
>>> print(n.zfill(3))
004

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.

Best way to format integer as string with leading zeros?

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

How to pad a numeric string with zeros to the right in Python?

See Format Specification Mini-Language:

In [1]: '{:<08d}'.format(190)
Out[1]: '19000000'

In [2]: '{:>08d}'.format(190)
Out[2]: '00000190'

Add leading zeroes to a string Python

There is a built-in, the str.ljust() method. It takes the target width and an optional fill character (defaulting to a space). You can use it to pad out a string with '0' characters:

val = val.ljust(8, '0')

There is also an equivalent str.rjust() method to add padding on the left.

However, if you want leading zeros (as opposed to trailing), I'd use the str.zfill() method as that takes any - or + prefix into account.

How to add leading zeros to ip address using python

You can use this:

ip = '1.2.3.4'
'.'.join(i.zfill(3) for i in ip.split('.'))

'001.002.003.004'

How to pad a number with leading zeros in the middle of a string?

You can use format specifications:

lst = ['KOI-234', 'KOI-123', 'KOI-3004', 'KOI-21', 'KOI-4325']

['{}-{:0>4}'.format(*i.split('-')) for i in lst]
# ['KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']

If you want to remove leading zeros:

[f'{i}-{int(j)}' for i, j in map(lambda x: x.split('-'), lst)]

Python add leading zeroes using str.format

>>> "{0:0>3}".format(1)
'001'
>>> "{0:0>3}".format(10)
'010'
>>> "{0:0>3}".format(100)
'100'

Explanation:

{0 : 0 > 3}
│ │ │ │
│ │ │ └─ Width of 3
│ │ └─ Align Right
│ └─ Fill with '0'
└─ Element index


Related Topics



Leave a reply



Submit