banner ad

Built-in Funciton str() VS repr()

| January 25, 2013 | 0 Comments
0 Flares 0 Flares ×

The str() function is meant to return representations of values which are fairly human-readable, while
repr() is meant to generate representations which can be read by the interpreter (or will force a
SyntaxError if there is not equivalent syntax).
str()—>Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ”.
repr()—>Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
for an example:

>>> str(4.53-2j)
'(4.53-2j)'
>>>
>>> str(1)
'1'
>>>
>>> str(2e10)
'20000000000.0'
>>>
>>> str([0, 5, 9, 9])
'[0, 5, 9, 9]'
>>>
>>> repr([0, 5, 9, 9])
'[0, 5, 9, 9]'
>>>
>>> `[0, 5, 9, 9]`
'[0, 5, 9, 9]'
Download PDF
0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Reddit 0 StumbleUpon 0 0 Flares ×

Tags:

Category: Function

About the Author ()

My name is John Link.I am 26 years old. My major is Computer science and technology. I am a junior programmer with Python.

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Reddit 0 StumbleUpon 0 0 Flares ×