str()

The str type constructor — turn any object into human-readable text, or decode bytes into a proper string.

Built-in functionPython 1.0+Live demo
Common call
str(value)
Returns
always a str — safe on any input
Replaces
the older `repr()` when human display is wanted, not debugging
Watch out
str(None) is "None"; str([1,2]) is "[1, 2]" — great for display, wrong for parsing
str(objectobjectAny value. No argument returns the empty string. For most types Python calls __str__(); if missing, falls back to __repr__().type: Any · default: ""='', encodingencodingOnly used when object is bytes or bytearray. Decodes the raw bytes as text.type: str · default: "utf-8"='utf-8', errorserrorsOnly used with bytes. Controls how decoding errors are handled — "strict" raises, "ignore" drops, "replace" substitutes.type: str · default: "strict"='strict')
str

Demo

Live evaluation
Try:
Inputs
xstrany value
Output
str('hello')
'hello'

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

NameTypeRequiredDescription
objectAnyno ("")Any value. No argument returns the empty string. For most types Python calls __str__(); if missing, falls back to __repr__().
encodingstrno ("utf-8")Only used when object is bytes or bytearray. Decodes the raw bytes as text.
errorsstrno ("strict")Only used with bytes. Controls how decoding errors are handled — "strict" raises, "ignore" drops, "replace" substitutes.

Return value

strA 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

Coerce for concatenation
Python does not auto-convert; strings and numbers cannot be joined with `+`.
msg = "count = " + str(count)
Decode raw bytes
Explicit encoding is safer than the implicit default.
text = str(payload, encoding="utf-8", errors="replace")
Human-readable dict / list
str() on collections gives a Python-literal display — good for logs, wrong for JSON.
print("state:", str(config))   # {'host': 'dev'}

Examples

1. Empty default
str()
Returns
""
2. Integer
str(42)
Returns
"42"
3. Float
str(3.14)
Returns
"3.14"
4. None becomes text
str(None)
Returns
"None"
5. List looks like source
str([1, 2, 3])
Returns
"[1, 2, 3]"
6. Dict looks like source
str({"a": 1})
Returns
"{'a': 1}"
7. Decode bytes
str(b"caf\xc3\xa9", "utf-8")
Returns
"café"
8. Bytes with no encoding
str(b"hi")
Returns
"b'hi'" # NOT decoded

Pitfalls

1. str(bytes) WITHOUT encoding gives the repr
The single-arg form does not decode — it wraps the bytes as `b'...'` text. To decode, always pass encoding.
Wrapped repr
str(b"hello")
"b'hello'" # not "hello"
Decode
str(b"hello", "utf-8")
"hello"
2. str(None) is "None", not "" or an error
Handy for logging, but confusing when a nullable field ends up rendered as the four-letter word "None" in your UI.
Ugly UI
label = "user: " + str(user_id)   # user_id is None
"user: None"
Guard first
label = "user: " + (str(user_id) if user_id is not None else "?")
"user: ?"
3. str() is NOT the JSON serializer
str() on a dict uses Python single-quote repr — not valid JSON. Use json.dumps for interchange.
Invalid JSON
str({"a": 1})
"{'a': 1}" # single quotes
Real JSON
import json
json.dumps({"a": 1})
'{"a": 1}' # double quotes
4. str vs repr — different intents
str is for humans, repr is for debugging. For most user-defined classes, only __repr__ is defined; str() falls back to it. Custom __str__ separates display from debug.
Same output
class Point:
    def __repr__(self): return f"Point({self.x}, {self.y})"

str(Point(1, 2))
"Point(1, 2)" # repr fallback
Define __str__
class Point:
    def __repr__(self): return f"Point({self.x}, {self.y})"
    def __str__(self):  return f"({self.x}, {self.y})"
"(1, 2)"

When to use

Use it
  • 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
Reach for something else
  • 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

Complexity
Depends on the type — usually O(n) in the resulting text length
Return
str — always
CPython impl
Objects/unicodeobject.c :: unicode_new — dispatches to __str__ then __repr__
Memory
Allocates one string
Thread-safe
Yes — a pure computation

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.

History

1.0
str() has been a builtin since Python 1.0.
3.0
str became Unicode by default; bytes became a separate type; decoding requires explicit encoding.