+ 3

Can anyone help what is the difference between str and rep in python

pls can you give useful examples.

7th May 2017, 4:50 AM
Sriram Chowdary Mellamputi
Sriram Chowdary Mellamputi - avatar
7 Réponses
+ 6
Unambigous means precise, accurate, not leaving doubts to what is what. For example: "May 7th, 2017", although we know it represents a date, is just a string to Python, unless you declare it a class of your own. Then you might define __repr__ to return a tuple or a list of day, month, year (so it can be clear what is what - use __repr__ and be as verbose as you like) and still wanting to print it out to the user as a string (that's basically what __str__ is for).
7th May 2017, 6:26 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 9
In most of the cases, really vague. __str__ is meant to give a human-readable string (mainly for printing), while __repr__ is thought to give the best, unambigous representation. __str__ will return '100' from both a string '100' and a number 100 - it is readable but not unambigous. __repr__ will differentiate what is what. If you put it as an argument to eval() method and give it an object as its own argument, the expression will return the very object. Fortunately, both __str__ and __repr__ can be overridden and return whatever you need :)
7th May 2017, 5:40 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
awesome explanations Kuba :)
7th May 2017, 8:17 AM
Burey
Burey - avatar
+ 5
No problem, pls tick my answer with a ✅ if it helped you, TIA ;)
7th May 2017, 8:02 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 3
thank you very much for your useful info.. pls could you explain what is unambiguous ?
7th May 2017, 6:19 AM
Sriram Chowdary Mellamputi
Sriram Chowdary Mellamputi - avatar
+ 3
sure
7th May 2017, 8:03 AM
Sriram Chowdary Mellamputi
Sriram Chowdary Mellamputi - avatar
+ 2
thanks..Kuba. really good explanation.
7th May 2017, 7:05 AM
Sriram Chowdary Mellamputi
Sriram Chowdary Mellamputi - avatar