String Conversion

str(obj)

  • Creates a printable string (same output as produced by print)

repr(obj)

  • Creates a string representation that can be converted back into the original object
  • Shorthand version is specified with backquotes `obj`
     s = repr(obj)
     a = `obj`         # Same thing
  • Note: In general, eval(repr(obj)) = obj
  • Often str() and repr() are the same.
  • However, this isn't guaranteed (e.g., strings).
     a = "Hello World\n"
     print str(a)        # Prints "Hello World"  (with newline)
     print repr(a)       # Prints "Hello World\012"
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 49
July 17, 2000, beazley@cs.uchicago.edu
>>>