The zfill method

The zfill method returns a string filled with zeros to a given length. The desired string length is specified by the method parameter.

Syntax

pythonstring.zfill(string length)

Example

Let's apply the zfill method to our string:

pythontxt = 'abc'
print(txt.zfill(6))

Result of code execution:

python'000abc'

Example

Let's use the zfill method again, but in this case, we'll specify a number in the parameter that is less than the length of our string:

pythontxt = 'abc'
print(txt.zfill(2))

As you can see from the result, we got back the original string:

python'abc'

See also

  • method ljust,
    which aligns and fills the text in a line to the left
  • method rjust,
    which aligns and fills the text in a line to the right
  • function len,
    which returns the length of the string