Pading a string with zfill method in Python

Padding a string

We can pad a string with zfill method. zfill method has the following syntax.

s.zfill(width)

Pads string s on left with zero digits to produce a string result of the desired width.


import string
print string.zfill('12', 5)
print string.zfill('-3.14', 7)
print string.zfill('3.14159265359', 5)

The code above generates the following result.

It understands about plus and minus signs:


print '12'.zfill(5)
print '-3.14'.zfill(7)
print '3.14159265359'.zfill(5)
# Using the % operator looks like this:
import math
print 'The value of PI is approximately %5.3f.' % math.pi

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary