Python: Print with Percent Format String

By Xah Lee. Date: . Last updated: .

Print with Percent Format String

the print function can take arguments for the purpose of formating values.

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

# format string

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

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

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

2012-03-25 Thanks to Yuri Khan for tip on Python print.

Python, format string

python print