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
str.rjust
Returns the string right-justified in a field of the given width, padded on the left with fillchar. Returns the original string unchanged if it is already at least width characters long.
str.center
Returns the string centered in a field of the given width, padded on both sides with fillchar. When padding is uneven, the extra pad placement depends on the parity of width and margin — for the common odd-width case, it lands on the LEFT.
str.format
Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.
str.strip
Returns a copy of the string with leading and trailing whitespace removed. If chars is given, removes any leading/trailing characters that appear in the chars set (not a prefix/suffix — it is a character set).
str.lstrip
Returns a copy of the string with leading characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the left.