All tutorials for the difference between str() and repr() state that repr() returns machine-readable code. But I don't understand why having quotations around the return string makes for more machine readable code. In both cases, they return a string variable that can automatically be inserted into another piece of code automatically without doing any sort of processing on the string. Can you give me an example of when those quotations around the repr() string would be helpful in coding such that you would HAVE to use repr() over the str() variant? Sorry if this seems like a stupid question.
-
I don't think it does add quotations in all situations. e.g `print(repr([]))` does not print any quotations for me. Can you give an example? – Nick ODell Mar 16 '23 at 20:32
-
Does this answer your question? [What is the difference between \_\_str\_\_ and \_\_repr\_\_?](https://stackoverflow.com/questions/1436703/what-is-the-difference-between-str-and-repr) – luk2302 Mar 16 '23 at 20:32
-
2How else would you know the difference between 1 and '1' and [] and '[]'? – trincot Mar 16 '23 at 20:33
-
@NickODell they asked about repr() of strings specifically – mkrieger1 Mar 16 '23 at 20:33
1 Answers
Whenever possible, repr
returns a string that consists of valid Python code. That means that you could take the output of repr
, copy it into another Python program (or REPL session) verbatim, and run it, and you'd get something equal to the original value back. This isn't true for str
. For instance, if I call str("ABC")
, that produces ABC
, which is not a valid Python expression unless ABC
happens to be a variable in the current scope (and even if it does, it's unlikely to be equal to our original string). But repr("ABC")
produces 'ABC'
, with actual quotation marks around it. You could copy that text and literally paste it into another Python program to get something equal to the original string back.
Python does this wherever it's reasonable. Lists print out using valid Python syntax, and tuples do it as well. @dataclass
-annotated classes produce valid Python expressions as their repr
. The only class I can think of offhand that has distinct str
and repr
is str
itself, though I'm sure there are others. And many user-defined classes will do the same. It's common in introductory courses to see a class like Person
, where repr
is a valid Python expression to produce the person object while str
returns the person's name or some other "summary" information.

- 62,821
- 6
- 74
- 116
-
Okay, I'll try to remember that it returns a value that can be copy and pasted directly into another piece of source code. – Mezzoforte Mar 16 '23 at 20:41