33

what is the difference between str() and repr() functions in python 2.7.5?

Explanation on python.org:

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 no equivalent syntax)

But it wasn't clear for me.

some examples:

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"      # repr is giving an extra double quotes
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'  # repr is giving value with more precision

so I want to know the following

  1. When should I use str() and when should I use repr()?
  2. In which cases I can use either of them?
  3. What can str() do which repr() can't?
  4. What can repr() do which str() can't?
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
AnV
  • 2,794
  • 3
  • 32
  • 43
  • 2
    `repr` should return the *Python "object representation"* that evaluates to such object, as applicable. This is why the string is quoted when using `repr`: so `eval(repr(someStr)) == someStr` should is true (it would also have nicely escaped unprintable and control characters). It (`repr` and reprlib) is useful for *debugging* and *exploring* objects, but should generally not be used for end-user output. – user2864740 Oct 12 '13 at 06:52
  • check this http://satyajit.ranjeev.in/2012/03/14/python-repr-str.html and http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python – Zaz Gmy Oct 12 '13 at 06:53
  • Note that when you just type str(s) in the interpreter, it's printing out repr(str(s)), because the interpreter displays the repr of any expression you type. `print str(s)` and `print repr(s)` and you might find it more enlightening. – abarnert Oct 12 '13 at 06:59
  • Note that in your numbers example, `repr()` may be giving you a higher precision, but not necessarily a higher accuracy. It does show more digits, but because of typical floating point limitations, the value shown by `str()` may be better. Compare `repr(sum(0.1 for i in range(9)))` and `str(sum(0.1 for i in range(9)))`. On the other hand, `str()` will hide the inherent inaccuracy from you, which confuses people who wonder why `sum(0.1 for i in range(9)) == 0.9` returns `False`... – Tim Pietzcker Oct 12 '13 at 07:19
  • 1
    @hcwhsa I didn't understand why my question is duplicate.I saw the link which you gave.But there the explanation was given using classes,self. I am an absolute beginner of python. I didn't even understand it.And my doubt is on functions and i clearly explained it.So can you please reconsider my question ? – AnV Oct 13 '13 at 12:25
  • I have to agree with @vnvmabhinav. His question seeks answer as a Python language beginner, a noob who has just started reading The Python Tutorial. The link that you have provided explains more about the implementations and intentions of __str__ and __repr__ in class definitions. I .. just hate this. :( Well, its 3 and 1/2 years later, so I shouldn't complain. – John Red Feb 05 '16 at 11:31

1 Answers1

31

When should i use str() and when should i use repr() ?

Almost always use str() when creating output for end users.

repr() is mainly useful for debugging and exploring. For example, if you suspect a string has non printing characters in it, or a float has a small rounding error, repr() will show you; str() may not.

repr() can also be useful for generating literals to paste into your source code. It can also be used for persistence (with ast.literal_eval or eval), but this is rarely a good idea--if you want editable persisted values, something like JSON or YAML is much better, and if you don't plan to edit them, use pickle.

2.In which cases i can use either of them ?

Well, you can use them almost anywhere. You shouldn't generally use them except as described above.

3.What can str() do which repr() can't ?

Give you output fit for end-user consumption--not always (e.g., str(['spam', 'eggs']) isn't likely to be anything you want to put in a GUI), but more often than repr().

4.What can repr() do which str() can't

Give you output that's useful for debugging--again, not always (the default for instances of user-created classes is rarely helpful), but whenever possible.

And sometimes give you output that's a valid Python literal or other expression--but you rarely want to rely on that except for interactive exploration.

Community
  • 1
  • 1
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • You said: "`repr` can also be useful for for generating literals to paste into your source code." Another way to do this would be to use what are called [Raw Strings](https://docs.python.org/2/tutorial/introduction.html#strings). – John Red Feb 06 '16 at 06:10
  • @RedJohn Raw strings literals don't do anything like the same thing. There may be a tiny bit of overlap (if you don't know how to escape a string, you should probably use a raw string, but you could instead use repr to show you how to escape it), but that's it. – abarnert Feb 06 '16 at 06:13
  • Agreed. I was just talking about that one similarity. I am not claiming any more. I, for one, make mistakes when writing file names in source code; especially in Windows where there are backslashes in file names. So, there I use raw strings instead of copy-pasting the proper escape-sequenced string using repr() in the interpreter. – John Red Feb 06 '16 at 06:26