Check a string is utf-8 encoded

    :param bytes txt: utf-8 string
    :return: Whether the string\
    is utf-8 encoded or not
    :rtype: bool
506143
def _is_utf_8(txt):
    
    assert isinstance(txt, six.binary_type)

    try:
        _ = six.text_type(txt, 'utf-8')
    except (TypeError, UnicodeEncodeError):
        return False
    else:
        return True
221530
def to_utf8(str_or_unicode):
    
    if not isinstance(str_or_unicode, six.text_type):
        return str_or_unicode.encode("utf-8", "ignore")
    return str(str_or_unicode)
1229715
def decode_bytes(string):
    

    if is_string_type(type(string)):
        string = bytes(string, "utf-8")
    return base64.decodebytes(string)
522677
def encode(value, encoding='utf-8', encoding_errors='strict'):
    
    if isinstance(value, bytes):
        return value
    if not isinstance(value, basestring):
        value = str(value)
    if isinstance(value, unicode):
        value = value.encode(encoding, encoding_errors)
    return value
42779
def to_utf8(string):
    
    if isinstance(string, six.text_type):
        return string.encode('utf8')
    if isinstance(string, six.binary_type):
        return string
    return str(string)
1304980
def force_bytes(s, encoding='utf-8', errors='strict'):
    
    # Handle the common case first for performance reasons.
    if isinstance(s, bytes):
        if encoding == 'utf-8':
            return s
        else:
            return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s.encode(encoding, errors)
160112
def text(self,txt):
        
        if not txt:
            return
        try:
            txt = txt.decode('utf-8')
        except:
            try:
                txt = txt.decode('utf-16')
            except:
                pass

        self.extra_chars = 0
        
        def encode_char(char):  
            """ 
            Encodes a single utf-8 character into a sequence of 
            esc-pos code page change instructions and character declarations 
            """ 
            char_utf8 = char.encode('utf-8')
            encoded  = ''
            encoding = self.encoding # we reuse the last encoding to prevent code page switches at every character
            encodings = {
                    # TODO use ordering to prevent useless switches
                    # TODO Support other encodings not natively supported by python ( Thai, Khazakh, Kanjis )
                    'cp437': TXT_ENC_PC437,
                    'cp850': TXT_ENC_PC850,
                    'cp852': TXT_ENC_PC852,
                    'cp857': TXT_ENC_PC857,
                    'cp858': TXT_ENC_PC858,
                    'cp860': TXT_ENC_PC860,
                    'cp863': TXT_ENC_PC863,
                    'cp865': TXT_ENC_PC865,
                    'cp866': TXT_ENC_PC866,
                    'cp862': TXT_ENC_PC862,
                    'cp720': TXT_ENC_PC720,
                    'cp936': TXT_ENC_PC936,
                    'iso8859_2': TXT_ENC_8859_2,
                    'iso8859_7': TXT_ENC_8859_7,
                    'iso8859_9': TXT_ENC_8859_9,
                    'cp1254'   : TXT_ENC_WPC1254,
                    'cp1255'   : TXT_ENC_WPC1255,
                    'cp1256'   : TXT_ENC_WPC1256,
                    'cp1257'   : TXT_ENC_WPC1257,
                    'cp1258'   : TXT_ENC_WPC1258,
                    'katakana' : TXT_ENC_KATAKANA,
            }
            remaining = copy.copy(encodings)

            if not encoding :
                encoding = 'cp437'

            while True: # Trying all encoding until one succeeds
                try:
                    if encoding == 'katakana': # Japanese characters
                        if jcconv:
                            # try to convert japanese text to a half-katakanas 
                            kata = jcconv.kata2half(jcconv.hira2kata(char_utf8))
                            if kata != char_utf8:
                                self.extra_chars += len(kata.decode('utf-8')) - 1
                                # the conversion may result in multiple characters
                                return encode_str(kata.decode('utf-8')) 
                        else:
                             kata = char_utf8
                        
                        if kata in TXT_ENC_KATAKANA_MAP:
                            encoded = TXT_ENC_KATAKANA_MAP[kata]
                            break
                        else: 
                            raise ValueError()
                    else:
                        encoded = char.encode(encoding)
                        break

                except ValueError: #the encoding failed, select another one and retry
                    if encoding in remaining:
                        del remaining[encoding]
                    if len(remaining) >= 1:
                        encoding = remaining.items()[0][0]
                    else:
                        encoding = 'cp437'
                        encoded  = '\xb1'    # could not encode, output error character
                        break;

            if encoding != self.encoding:
                # if the encoding changed, remember it and prefix the character with
                # the esc-pos encoding change sequence
                self.encoding = encoding
                encoded = encodings[encoding] + encoded

            return encoded
        
        def encode_str(txt):
            buffer = ''
            for c in txt:
                buffer += encode_char(c)
            return buffer

        txt = encode_str(txt)

        # if the utf-8 -> codepage conversion inserted extra characters, 
        # remove double spaces to try to restore the original string length
        # and prevent printing alignment issues
        while self.extra_chars > 0: 
            dspace = txt.find('  ')
            if dspace > 0:
                txt = txt[:dspace] + txt[dspace+1:]
                self.extra_chars -= 1
            else:
                break

        self._raw(txt)
495562
def ensureUtf(s, encoding='utf8'):
    
    # In Python2, str == bytes.
    # In Python3, bytes remains unchanged, but str means unicode
    # while unicode is not defined anymore
    if type(s) == bytes:
        return s.decode(encoding, 'ignore')
    else:
        return s
798415
def _convert_string_to_unicode(string):
    
    result = string

    try:
        if string is not None and not isinstance(string, six.text_type):
            result = string.decode('utf-8')
    except (TypeError, UnicodeDecodeError, AttributeError):
        # Sometimes the string actually is binary or StringIO object,
        # so if you can't decode it, just give up.
        pass

    return result
252200
def to_unicode(s):
    
    if not isinstance(s, TEXT):
        if not isinstance(s, bytes):
            raise TypeError('You are required to pass either unicode or '
                            'bytes here, not: %r (%s)' % (type(s), s))
        try:
            s = s.decode('utf-8')
        except UnicodeDecodeError as le:
            raise TypeError('You are required to pass either a unicode '
                            'object or a utf-8-encoded bytes string here. '
                            'You passed a bytes object which contained '
                            'non-utf-8: %r. The UnicodeDecodeError that '
                            'resulted from attempting to interpret it as '
                            'utf-8 was: %s'
                            % (s, le,))
    return s
379878
def bytes_to_unicode(s, encoding='utf-8', errors='replace'):
    
    if compat.PY3:
        return str(s, 'utf-8') if isinstance(s, bytes) else s
    return s if isinstance(s, unicode) else s.decode(encoding, errors)
1299548
def read_utf8_string(self, length):
        
        s = struct.unpack("%s%ds" % (self.endian, length), self.read(length))[0]

        return s.decode('utf-8')
801398
def try_utf8_decode(value):
    
    if not value or not is_string(value):
        return value
    elif PYTHON3 and not isinstance(value, bytes):
        return value
    elif not PYTHON3 and not isinstance(value, unicode):
        return value

    try:
        return value.decode('utf-8')
    except UnicodeDecodeError:
        pass

    return value
590676
def ensure_text(str_or_bytes, encoding='utf-8'):
    
    if not isinstance(str_or_bytes, six.text_type):
        return str_or_bytes.decode(encoding)
    return str_or_bytes
1113636
def to_bytes(s):  # pragma: nocover
    
    if isinstance(s, bytes):
        return s
    if isinstance(s, str) or is_unicode(s):
        return s.encode("utf-8")
    try:
        return unicode(s).encode("utf-8")
    except NameError:
        return str(s).encode("utf-8")
930355
def ensure_str(data: Union[str, bytes]) -> str:
    
    if isinstance(data, bytes):
        return str(data, 'utf-8')

    return data
178384
def is_unicode_string(string):
    
    if string is None:
        return None
    if PY2:
        return isinstance(string, unicode)
    return isinstance(string, str)