def to_binary ( s , encoding = 'utf8' ) : if PY3 : # pragma: no cover return s if isinstance ( s , binary_type ) else binary_type ( s , encoding = encoding ) return binary_type ( s )
encoding a string to binary in python
Portable cast function .
def to_binary(s, encoding='utf8'):
    """Portable cast function.

    In python 2 the ``str`` function which is used to coerce objects to bytes does not
    accept an encoding argument, whereas python 3's ``bytes`` function requires one.

    :param s: object to be converted to binary_type
    :return: binary_type instance, representing s.
    """
    if PY3:  # pragma: no cover
        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)
    return binary_type(s)