This guide explains str() vs repr(): Human-Friendly and Developer-Friendly Output through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
str() is intended for a readable display; repr() aims to reveal an unambiguous representation for developers. Escape sequences and quotes make repr() particularly helpful when debugging whitespace.
When You Would Use This
Diagnose a username that contains trailing newline characters.
Step-by-Step Example
entered_name = "Avery\n"
print(str(entered_name))
print(repr(entered_name))
How the Example Works
Normal display creates a visible line break. The developer representation shows quotation marks and an escaped \n, exposing the hidden character.
Example Output
Avery
'Avery\n'
Try It Yourself
Compare str() and repr() for a string containing a tab.
Common Beginner Mistakes
- Using
repr()as the final user-facing label. - Assuming the output of every custom
repr()is executable code. - Forgetting that both functions return a new string.
Key Takeaways
str()is intended for a readable display;repr()aims to reveal an unambiguous representation for developers.- Normal display creates a visible line break.
- Avoid this mistake: Using
repr()as the final user-facing label.