Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

str: a text representation of an object

str creates a Unicode string. Converting a number to text does not perform arithmetic, and turning bytes into text requires a deliberate choice of encoding.

Version: Python 3.14

Syntax

str()
str(object)
str(object, encoding, errors='strict')

str(23) produces the text "23". Joining it with "5" therefore produces "235", not a numeric sum. Strings are immutable: methods that return changed text produce a result instead of modifying an individual character in the existing string. str() without arguments produces an empty string.

For objects, str uses their readable representation, defined by __str__. repr serves a different purpose: a representation useful for debugging. Do not assume that every string obtained from an object can later be converted back without loss.

str(b"ok") displays the representation of the bytes object, including its b marker, instead of decoding its contents. str(b"ok", "utf-8") decodes bytes using the specified encoding. Invalid bytes with the default strict mode raise UnicodeDecodeError; ignoring errors can lose data.

The example shows these two routes separately. str does not provide HTML escaping, SQL protection or a safe interchange format. Choose a suitable mechanism for those purposes, such as query parameters or JSON serialization.

Examples

print(str(23) + "5")
print(str(b"ok"))
print(str(b"ok", "utf-8"))
try:
    str(b"\xff", "utf-8")
except UnicodeDecodeError:
    print("UnicodeDecodeError")

Result

235
b'ok'
ok
UnicodeDecodeError

Sources