Store Unicode text
Representing names, labels, messages, and other textual application data.
Python · Class
str is Python’s immutable Unicode text type and sequence of code points. Its constructor creates printable text from objects or decodes bytes when an encoding is supplied.
str is Python’s immutable text sequence type, storing Unicode code points. The constructor can either produce an object’s printable string form or decode bytes when an encoding is supplied; indexing returns strings of length one.
class str(object)
class str(object, encoding='utf-8', errors='strict')| Name | Type | Description |
|---|---|---|
object | object | The value to convert; omitted to produce an empty string. |
encoding | str | The character encoding used when converting bytes to text. |
errors | str | The policy for handling encoding or decoding errors; defaults to strict. |
A str representation of the object, or decoded text when encoding is supplied.
name = "Ada"
age = 36
text = f"{name} is {age}"
print(text[0])
print(str(age))
print(text == "Ada is 36")Creates a Unicode string, indexes it to obtain a one-character string, and converts an integer to str.
Representing names, labels, messages, and other textual application data.
Converting numbers or custom values for display and logging.
Turning encoded byte data into Python text at an I/O boundary.
Building output from many pieces efficiently.
str represents textual data as an immutable sequence of Unicode code points. Because strings are sequences, they support indexing, slicing, and iteration; an indexed result is itself a string.
Follow-up: What does str(x) do when x is not already a string? It normally calls x.__str__(), falling back to repr(x) if no __str__() method exists.
With only an object argument, str(object) returns its informal, printable representation. If no object is supplied, the result is the empty string.
Follow-up: How can bytes be converted to text? Supply an encoding, and optionally an error-handling policy, such as str(data, encoding="utf-8").
A str can be constructed from bytes by providing an encoding and optionally errors. The documented constructor defaults encoding to utf-8 and errors to strict in that form.
Follow-up: Why should decoding be explicit at boundaries? It makes the byte-to-text encoding choice visible and lets the caller select an appropriate error policy.
bytesrepr()str.join()io.StringIO__str__()