Representing data

Why do you sometimes see different results when you type name and when you type print name? Just typing name and pressing Return is a shortcut for using the function repr() to display the result, whereas the print command uses the function str() to display the result.

In technical terms, when you type an object name, literal, expression, or statement and press Return, Python evaluates the object. That is, Python runs the code and returns/displays the result.

According to Python's built-in documentation, the function str() returns a "nice" string representation of an object. The function repr() returns the "canonical" string representation of the object. Here's the difference between a "nice" and a "canonical" representation of a floating point number:

>>> 3.2

#

canonical

3.2000000000000002

>>> str(3.2)

#

nice

'3. 2'

>>> repr(3.2)

#

canonical

'3.2000000000000002'

>>> print 3.2

#

nice

3.2

The canonical representation usually tries to be a chunk of text that, when pasted into the interpreter, re-creates the object. This example shows how:

True

(Note that some objects, such as files, can't be re-created by repr(). You can still use the output of repr() as debugging info when working with such objects.)

Here's an example of what str() and repr() return when you give them a class as an argument:

>>> str(Message) ' main .Message' >>> repr(Message)

'<class main .Message at 0x58e40>'

Was this article helpful?

0 0

Post a comment