Zfill() method of str class

Method Name:

zfill

 

Method Signature:

zfill(stringWidth)

 

Method Overview:

  • zfill() method prefixes a string of width 'w' with zeroes and returns a copy of the string object.

 

  • The width is specified by the parameter stringWidth

 

  • If the string has a + or - sign, the padding or prefixing starts after the sign.

 

  • If the length of the string is less than equal to the width then the original string is returned.

 

Example:

# ==========Sample Python program for zfill()==========

 

text = "73"

zfilled = text.zfill(5)

print("Zero filled/prefixed:%s"%(zfilled))

 

# When string contents starts with a sign

text = "-3"

zfilled = text.zfill(5)

print("Zero filled when string has a sign:%s"%(zfilled))

 

# works for alphabets as well

text = "+abc"

zfilled = text.zfill(5)

print("Zero filled when string has a sign:%s"%(zfilled))

 

# will return the original string as (width == length) is True

text = "37"

zfilled = text.zfill(2)

print("Zero filled/prefixed:%s"%(zfilled))

 

Output:

Zero filled/prefixed:00073

Zero filled when string has a sign:-0003

Zero filled when string has a sign:+0abc

Zero filled/prefixed:37

 


Copyright 2024 © pythontic.com