Python 3 reference · Built-in Functions

Python str() Function

Convert a value to its readable text form, or decode bytes into a string. Strings are immutable sequences of characters.

Python 3 Since 3.0

Syntax

str(object="")
str(object=b"", encoding="utf-8", errors="strict")

Parameters

ParameterDescription
object optional Any value; for bytes, pass an encoding to decode. Default: ""
encoding optional Decode bytes with this encoding.
errors optional How to handle decoding errors. Default: "strict"

Return value

A str.

Examples

Convert values to textTry it yourself
print(str(42) + " apples")
print(str(3.5), str(True), str([1, 2]))

Output

42 apples
3.5 True [1, 2]
Decode bytesTry it yourself
data = b"caf\xc3\xa9"
print(str(data, "utf-8"))
print(data.decode())  # the more common spelling

Output

café
café
Building messagesTry it yourself
age = 36
print("Age: " + str(age))
print(f"Age: {age}")  # usually nicer

Output

Age: 36
Age: 36

Common mistakes

  • "Total: " + 5 raises TypeError; convert with str(5) or use an f-string.
  • str(b"abc") without an encoding gives "b'abc'", not "abc". Decode bytes with .decode().

Version history

VersionChange
Python 3.0Added