what is the difference between
Thefunction is meant to return representations of values which are fairly human-readable, while
str()is meant to generate
representations which can be read by the interpreter (or will force aif there is no equivalent syntax)
>>> s = 'Hello, world.'
"'Hello, world.'" # repr is giving an extra double quotes
'0.14285714285714285' # repr is giving value with more precision
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
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.
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
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.