This guide explains repr() Function: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
repr(value) returns a developer-oriented representation. For strings it often includes quotes and escape characters, making it useful for diagnostics when invisible whitespace or special characters are involved.
When You Would Use This
Compare normal display with a representation of a string containing a newline.
Step-by-Step Example
message = "Line one\nLine two"
print(str(message))
print(repr(message))
How the Example Works
The first call displays two lines. The second displays quotes and \n, revealing the newline character rather than rendering it as a line break.
Example Output
Line one
Line two
'Line one\nLine two'
Try It Yourself
Try a value containing a tab and compare the two display styles.
Common Beginner Mistakes
- Assuming every object’s
repr()output is valid Python source. - Using
repr()for end-user messages when readablestr()is preferable. - Confusing a newline escape in
repr()with two characters stored in the string.
Key Takeaways
repr(value)returns a developer-oriented representation.- The first call displays two lines.
- Avoid this mistake: Assuming every object’s
repr()output is valid Python source.