Python: Percent Format String

By Xah Lee. Date: . Last updated: .

Print with Percent Format String

the print also let you format the string.

The syntax is:

print(str % (arg1, arg2, etc))

Example, format integer

# integer
print("%d" % (1234))
# 1234

# padding by space
print("(%4d)" % (12))
# (  12)

Example, format float

# float. 2 place for integer, 4 for decimal
print("(%2.4f)" % (3.123456789))
# (3.1235)

Example, format string

# string
print("(%5s)" % ("cats"))
# ( cats)

print("(%2s)" % ("cats"))
# (cats)

Python, format string