def to_utf8(buf, errors='replace'):
    """ Encodes a string into a UTF-8 compatible, ASCII string.

        `buf`
            string or unicode to convert.

        Returns string.

        * Raises a ``UnicodeEncodeError`` exception if encoding failed and
          `errors` isn't set to 'replace'.
        """

    if isinstance(buf, unicode):
        return buf.encode('utf-8', errors)

    else:
        return buf