formatting

str.zfill

Returns a copy padded on the left with '0' digits to reach the given width. Unlike rjust('0'), it preserves a leading sign ('+' or '-') by placing the zeros after it.

str.zfill(width)

Parameters

Parameter Purpose
width minimum total width including any sign character
returns new str; original returned unchanged if already at least `width` long

Examples

>>> '42'.zfill(5)
'00042'

pads with leading zeros

>>> '-42'.zfill(5)
'-0042'

sign kept at the front (rjust would give '00-42')

>>> '3.14'.zfill(6)
'003.14'

works on any string, not just numbers

>>> 'abc'.zfill(2)
'abc'

no change when already wide enough

Gotcha

Only pads with '0' — no fillchar option. The sign-preserving behavior is what distinguishes it from rjust('0').

Related methods

← All Python string methods · Python built-ins