Python Bibliotheca
Python resources for teachers and students.

String formatting codes

Printing several variables in a single string is often easiest to do when you use the Python string formatting codes. The following table lists all of the formatting codes:

s string conversion (or any object) X hexadecimal integer (uppercase letters)
c character e exponential notation (with lowercase 'e')
d signed decimal integer E exponential notation (with uppercase 'E')
i integer f floating point real number
u unsigned decimal integer g the shorter of %f and %e
o octal integer G the shorter of %f and %E
x hexadecimal integer (lowercase letters) % literal '%'

You can modify the output further by adding to the basic codes.

Symbol Function
- left justify
m.n m is the minimum total width and n is the number of decimal digits to display (answer is rounded).
(var) maps a variable from a dictionary

Sample code

>>> import math
>>> math.pi
3.1415926535897931
>>> print '%s' % math.pi
3.14159265359
>>> print '%f' % math.pi
3.141593
>>> print '%.2f' % math.pi
3.14
>>> print '%10.2f' % math.pi
      3.14
>>> print '%e' % 300000000
3.000000e+008
>>> name = "Bob"
>>> age = 16
>>> print "My name is %s and I'm %s years old." % (name, age)
My name is Bob and I'm 16 years old.
>>> print "Name: %s Age: %s" % (name, age)
Name: Bob Age: 16
>>> print "Name: %10s Age: %s" % (name, age)
Name:        Bob Age: 16
>>> print "Name: %-10s Age: %s" % (name, age)
Name: Bob        Age: 16
>>> print "My name is %(name)s and I'm %(age)d years old." % \
      {'name': 'Bob', 'age': 16}
My name is Bob and I'm 16 years old.

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster