8.5 String Conversion
Converting numbers and collections to their string representation with str(), and why str() on a list or dict is debug-friendly but not what you'd show an end user.
str()
Converts virtually any object into its human-readable string representation — used constantly for logging, printing, and building messages.
>>> str(42)
'42'
Converting Numbers to Strings
>>> str(42), str(3.14), str(True)
('42', '3.14', 'True')
Converting Collections to Strings
str() on a list/dict/tuple produces a debug-friendly text representation matching how it would be typed as a literal — useful for logging, but not the format to show an end user (for that, format the contents explicitly).
>>> str([1, 2, 3])
'[1, 2, 3]'
>>> str({"a": 1})
"{'a': 1}"
Quick Interview Answer
“
str()converts virtually any object into its human-readable string form — for numbers that’s the obvious text representation, and for a collection it produces the same text you’d type to construct it as a literal (str([1, 2, 3])is'[1, 2, 3]'). That collection representation is meant for debugging and logging, not end-user display — showing a rawstr(some_dict)to a user is a common shortcut that reads poorly; format the contents deliberately instead.”
Common Mistakes
- Using
str(some_list)orstr(some_dict)directly in user-facing output instead of formatting the contents explicitly — technically works, but reads like debug output. - Forgetting
str(True)is'True'(capitalized), not'true'— a frequent source of bugs when building JSON-like text manually instead of using thejsonmodule.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form