String <-> bytes encoding/decoding

sage.cpython.string.bytes_to_str(b, encoding=None, errors=None)[source]

Convert bytes to str.

This decodes the given bytes to a Python 3 unicode str using the specified encoding. It is a no-op on str input.

EXAMPLES:

sage: from sage.cpython.string import bytes_to_str
sage: s = bytes_to_str(b'\xcf\x80')
sage: s == u'π'
True
sage: bytes_to_str([])
Traceback (most recent call last):
...
TypeError: expected bytes, list found
>>> from sage.all import *
>>> from sage.cpython.string import bytes_to_str
>>> s = bytes_to_str(b'\xcf\x80')
>>> s == u'π'
True
>>> bytes_to_str([])
Traceback (most recent call last):
...
TypeError: expected bytes, list found
sage.cpython.string.str_to_bytes(s, encoding=None, errors=None)[source]

Convert str or unicode to bytes.

It encodes the given str to a Python 3 bytes using the specified encoding. It is a no-op on bytes input.

EXAMPLES:

sage: from sage.cpython.string import str_to_bytes
sage: bs = [str_to_bytes(u'π')]
sage: all(b == b'\xcf\x80' for b in bs)
True
sage: str_to_bytes([])
Traceback (most recent call last):
...
TypeError: expected str... list found
>>> from sage.all import *
>>> from sage.cpython.string import str_to_bytes
>>> bs = [str_to_bytes(u'π')]
>>> all(b == b'\xcf\x80' for b in bs)
True
>>> str_to_bytes([])
Traceback (most recent call last):
...
TypeError: expected str... list found