encoding
str.encode
Returns a bytes object encoding the string using the named codec. Default encoding is UTF-8 and default error handling raises UnicodeEncodeError on characters that cannot be encoded.
str.encode(encoding='utf-8', errors='strict') Parameters
| Parameter | Purpose |
|---|---|
| encoding | codec name, e.g. 'utf-8', 'ascii', 'latin-1' |
| errors | 'strict' (default), 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' |
Examples
>>> 'hello'.encode()
b'hello' default UTF-8
>>> 'café'.encode('utf-8')
b'caf\xc3\xa9' non-ASCII gets multi-byte UTF-8
>>> 'café'.encode('ascii', errors='ignore')
b'caf' errors='ignore' drops unencodable chars
>>> 'café'.encode('ascii')
Traceback (most recent call last):
...
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128) strict mode raises on unencodable input
Gotcha
Returns bytes, not str — bytes.decode() is the inverse. Default is UTF-8 in Python 3; don't rely on the OS default. Use errors='replace' for lossy but safe encoding.
Related methods
str.format
Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.
str.replace
Returns a new string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced.
str.join
Returns a string built by concatenating every string in the iterable, separated by the string on which join is called. Every element of the iterable must be a str, or TypeError is raised.