str()
The str type constructor — turn any object into human-readable text, or decode bytes into a proper string.
Demo
The demo takes a text input and passes it through str() — for text sources this is essentially the identity function. In real code the interesting cases are: str(number) → decimal notation, str(list) → "[1, 2, 3]", str(None) → "None", str(bytes, encoding) → decoded text. The demo cannot show every type, but it does confirm str() never raises on well-formed input.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| object | Any | no ("") | Any value. No argument returns the empty string. For most types Python calls __str__(); if missing, falls back to __repr__(). |
| encoding | str | no ("utf-8") | Only used when object is bytes or bytearray. Decodes the raw bytes as text. |
| errors | str | no ("strict") | Only used with bytes. Controls how decoding errors are handled — "strict" raises, "ignore" drops, "replace" substitutes. |
Return value
str — A string representation of object. For most types this calls __str__(); for bytes it decodes using the given encoding. No argument returns the empty string.
Common patterns
msg = "count = " + str(count)
text = str(payload, encoding="utf-8", errors="replace")
print("state:", str(config)) # {'host': 'dev'}
Examples
Pitfalls
str(b"hello")
str(b"hello", "utf-8")
label = "user: " + str(user_id) # user_id is None
label = "user: " + (str(user_id) if user_id is not None else "?")
str({"a": 1})
import json json.dumps({"a": 1})
class Point: def __repr__(self): return f"Point({self.x}, {self.y})" str(Point(1, 2))
class Point: def __repr__(self): return f"Point({self.x}, {self.y})" def __str__(self): return f"({self.x}, {self.y})"
When to use
- Concatenating a value into a string message
- Converting between int/float/list and their text form
- Decoding bytes with an explicit encoding
- Building simple log lines or diagnostics
- JSON output → json.dumps
- Number formatting with control (padding, precision) → f-string or format spec
- User-facing text where None should not appear as "None" → guard first
- Serializing objects for storage → pickle or json
Notes
FAQ
str() is for humans — clean, presentable output. repr() is for debugging — unambiguous, often eval-able. For built-in types like int and str they usually match; for containers and custom classes they typically differ.