String Methods

str.encode()

Convert Unicode text into immutable bytes using a named text encoding. UTF-8 is the default and represents Persian letters as multibyte sequences. Decode using the corresponding encoding to recover the text when the conversion is lossless. The default strict policy raises UnicodeEncodeError for unrepresentable characters; ignore drops them, replace substitutes a codec-specific replacement, and backslashreplace produces escapes. Lossy policies cannot preserve the original data. Unknown encodings raise LookupError; an invalid error-handler name may only be detected when needed (or under development/debug mode). Encoding is not encryption and does not normalize text.

Formal Syntax & Structure

python syntaxpython
text.encode(encoding='utf-8', errors='strict')

Parameters & Attributes

NameTypeDescription
encodingstrText encoding name, default UTF-8.
errorsstrRegistered encoding-error policy; default strict.

Return Value

bytes

Encoded byte sequence; original text remains unchanged.

Working Example

Example Snippetpython
text = "سلام"encoded = text.encode("utf-8")print(len(text), len(encoded))print(encoded.hex())print(encoded.decode("utf-8"))print("Aé".encode("ascii", errors="replace"))
Python Reference