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

← All Python string methods · Python built-ins