String <-> bytes encoding/decoding¶
-
sage.cpython.string.
bytes_to_str
(b, encoding=None, errors=None)¶ Convert
bytes
tostr
.On Python 2 this is a no-op since
bytes is str
. On Python 3 this decodes the givenbytes
to a Python 3 unicodestr
using the specified encoding.EXAMPLES:
sage: import six sage: from sage.cpython.string import bytes_to_str sage: s = bytes_to_str(b'\xcf\x80') sage: if six.PY2: ....: s == b'\xcf\x80' ....: else: ....: s == u'π' True sage: bytes_to_str([]) Traceback (most recent call last): ... TypeError: expected bytes, list found
-
sage.cpython.string.
str_to_bytes
(s, encoding=None, errors=None)¶ Convert
str
orunicode
tobytes
.On Python 3 this encodes the given
str
to a Python 3bytes
using the specified encoding.On Python 2 this is a no-op on
str
input sincestr is bytes
. However, this function also accepts Python 2unicode
objects and treats them the same as Python 3 unicodestr
objects.EXAMPLES:
sage: import six sage: from sage.cpython.string import str_to_bytes sage: if six.PY2: ....: bs = [str_to_bytes('\xcf\x80'), str_to_bytes(u'π')] ....: else: ....: 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