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
| Parameter | Description |
|---|---|
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
print(str(42) + " apples")
print(str(3.5), str(True), str([1, 2]))
Output
42 apples 3.5 True [1, 2]
data = b"caf\xc3\xa9"
print(str(data, "utf-8"))
print(data.decode()) # the more common spelling
Output
café café
age = 36
print("Age: " + str(age))
print(f"Age: {age}") # usually nicer
Output
Age: 36 Age: 36
Common mistakes
"Total: " + 5raisesTypeError; convert withstr(5)or use an f-string.str(b"abc")without an encoding gives"b'abc'", not"abc". Decode bytes with.decode().
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
repr()· Return the developer-friendly string representation of an object, often valid Python code that recreates the value.format()· Format a single value with a format spec, such as format(3.14159, '.2f') giving '3.14'. The same mini-language as f-strings.bytes()· Create an immutable sequence of bytes: raw binary data such as file contents, network messages or encoded text.int()· Convert a number or string to an integer. Floats are truncated toward zero, and strings can be in any base from 2 to 36.- Python Strings · tutorial
- Python Casting · tutorial