Formatted I/O

The % operator for strings

     print "%d %f %s" % (42, 3.1415, "Hello")
     s = "Your name is '%s %s'" % (firstname, lastname)
  • Each of the format codes (preceded by %) are replaced by elements of a tuple
  • Works just like the C sprintf function

Format codes

     d,i             Decimal integer
     u               Unsigned integer
     o               Octal integer
     x               Hex integer
     X               Hex integer (uppercase letters)
     f               Floating point as [-]m.dddddd
     e               Floating point as [-]m.dddddde+xx
     E               Floating point as [-]m.ddddddE+xx
     g,G             Use e or f depending on the size of the exponent.
     s               String or any object
     c               Single character
     %               Literal character
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 117
July 17, 2000, beazley@cs.uchicago.edu
>>>