The str(object='') built-in function returns a human-readable string representation of an object or decodes raw bytes into text.
Textual Representation & Decoding: When called on objects, str() invokes their __str__() method (or falls back to __repr__()). When passed binary data with an encoding parameter, it decodes byte buffers according to specified error handling policies (strict, ignore, replace). For technical representations intended for debugging, see repr(). To format numbers into strings with precision control, use format().
The str() constructor provides two calling forms:
# Formal syntax of built-in str()
# Form 1: General object string conversion
text = str(object='')
# Form 2: Byte decoding with explicit encoding and error policy
decoded_text = str(bytes_or_buffer, encoding='utf-8', errors='strict')
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
object |
Any Python object | The object whose string representation is constructed. If omitted, returns empty string "". |
encoding |
str (optional) |
Encoding format (e.g. 'utf-8', 'ascii'). If supplied, object must be bytes or buffer. |
errors |
str (optional) |
Policy for decoding errors: 'strict', 'ignore', 'replace', 'backslashreplace'. |
| Return Value | str |
An immutable Unicode string object. |
Every standard Python object can be converted into a readable string representation:
# 1. Converting primitives and collections
print("str(3.4): ", str(3.4)) # '3.4'
print("str([1, 2]): ", str([1, 2])) # '[1, 2]'
print("str(True): ", str(True)) # 'True'
print("str(None): ", str(None)) # 'None'
print("str(3 + 4j): ", str(3 + 4j)) # '(3+4j)'
print("str({'a': 1}):", str({'a': 1})) # "{'a': 1}"
Output:
str(3.4): 3.4
str([1, 2]): [1, 2]
str(True): True
str(None): None
str(3 + 4j): (3+4j)
str({'a': 1}): {'a': 1}
When decoding raw bytes, str() accepts an encoding standard and error policy:
# Byte decoding with encoding and error policies
raw_bytes = b"plus2net.com ÿ þ"
# strict: default mode, raises UnicodeDecodeError on invalid bytes
try:
s = str(raw_bytes, encoding='utf-8', errors='strict')
except UnicodeDecodeError as err:
print("strict error caught:", err)
# ignore: skips malformed bytes silently
s_ignore = str(raw_bytes, encoding='ascii', errors='ignore')
print("errors='ignore': ", s_ignore.strip())
# replace: inserts Unicode replacement character \ufffd
s_replace = str(raw_bytes, encoding='utf-8', errors='replace')
print("errors='replace':", s_replace)
Output:
strict error caught: 'utf-8' codec can't decode byte 0xff in position 13: invalid start byte
errors='ignore': plus2net.com
errors='replace': plus2net.com � �
Python distinguishes between user-facing text and developer-facing representations:
| Feature | str(x) |
repr(x) |
|---|---|---|
| Target Audience | End users and clean interfaces | Developers, loggers, debuggers |
| Primary Objective | Readability and natural presentation | Unambiguous formal code representation |
| Dunder Method Called | __str__() (falls back to __repr__()) |
__repr__() |
| Eval Capability | Informational string | Ideally valid Python expression: eval(repr(x)) == x |
# str() vs repr(): user readability vs unambiguous code representation
import datetime
now = datetime.datetime(2026, 10, 15, 8, 30, 0)
# str() aims for readable human presentation
print("str(now): ", str(now))
# repr() aims for unambiguous, eval-ready technical representation
print("repr(now):", repr(now))
Output:
str(now): 2026-10-15 08:30:00
repr(now): datetime.datetime(2026, 10, 15, 8, 30)
Custom classes define their string conversion by implementing the __str__() dunder method:
# Custom classes implementing __str__() and __repr__()
class User:
def __init__(self, username: str, user_id: int):
self.username = username
self.user_id = user_id
def __str__(self) -> str:
# User-facing informal string
return f"User {self.username} (ID: {self.user_id})"
def __repr__(self) -> str:
# Developer-facing formal code representation
return f"User(username='{self.username}', user_id={self.user_id})"
u = User("alex_dev", 101)
print("str(u): ", str(u))
print("repr(u):", repr(u))
Output:
str(u): User alex_dev (ID: 101)
repr(u): User(username='alex_dev', user_id=101)
Below are real-world recipes utilizing str() for query serialization and log formatting:
# Recipe A: Safe serialization of mixed dictionaries
payload = {
"status": 200,
"active": True,
"ratio": 0.85,
"tag": None
}
# Formatted key-value query parameter string
query_str = "&".join(f"{k}={str(v)}" for k, v in payload.items())
print("Query string:", query_str)
# Recipe B: Robust multi-line logging formatter
def format_log_entry(level: str, message: object) -> str:
timestamp = "2026-10-15 08:30:00"
return f"[{timestamp}] [{level.upper()}] {str(message)}"
print(format_log_entry("info", {"processed": 45, "errors": 0}))
Output:
Query string: status=200&active=True&ratio=0.85&tag=None
[2026-10-15 08:30:00] [INFO] {'processed': 45, 'errors': 0}
encoding with non-bytes objects (e.g. str(123, encoding='utf-8')) raises a TypeError. Encoding is valid only for bytes.__str__() to return integers or booleans raises TypeError: __str__ returned non-string.+ is quadratic O(N^2). Use "".join(list_of_strings) for performance.# Pitfall 1: Calling str() with encoding on a non-bytes object
try:
str(12345, encoding='utf-8')
except TypeError as err:
print("TypeError caught:", err)
# Pitfall 2: Overriding __str__ returning non-string raises TypeError
class BadObj:
def __str__(self):
return 100 # Must return str!
try:
str(BadObj())
except TypeError as err:
print("TypeError caught:", err)
Output:
TypeError caught: decoding to str: need a bytes-like object, int found
TypeError caught: __str__ returned non-string (type int)
Practice string conversions, byte decoding, and __str__ vs __repr__ implementations in our companion Jupyter Notebook:
Explore interactive code cells, decode multi-byte buffers, implement custom __str__ representations, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify str() mechanics:
def test_str_mechanics():
# 1. Primitives
assert str(42) == "42"
assert str(3.14) == "3.14"
assert str(True) == "True"
assert str(None) == "None"
# 2. Byte decoding
assert str(b"hello", encoding="utf-8") == "hello"
assert str(b"hi ÿ", encoding="ascii", errors="ignore") == "hi "
# 3. Custom __str__
class Book:
def __str__(self): return "Python Guide"
assert str(Book()) == "Python Guide"
print("All str() unit assertions passed! 100% verified.")
test_str_mechanics()
Output:
All str() unit assertions passed! 100% verified.
Returns formal developer-facing string representation of an object.
Constructs immutable byte sequences from strings or integers.
Converts numeric values or strings into integer numbers.
Formats values using standard string formatting specifiers.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.