Returns the given value as a Unicode string (if possible).
169839
def decode_string(v, encoding="utf-8"):
    """"""
    if isinstance(encoding, basestring):
        encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore"))
    if isinstance(v, binary_type):
        for e in encoding:
            try:
                return v.decode(*e)
            except:
                pass
        return v
    return unicode(v)
68133
private String encode(String value) {
    return this.encode.isEncodingRequired() ? UriUtils.encode(value, this.charset) : value;
  }
1024147
def _Encode(self, value):
    """"""
    try:
      return value.SerializeToString().encode("hex")
    except AttributeError:
      if isinstance(value, (int, long)):
        return str(value).encode("hex")
      else:
        # Types "string" and "bytes" are stored as strings here.
        return utils.SmartStr(value).encode("hex")
885687
def _unicode(self):
        ''''''

        return u'\n'.join ([ u''.join(c) for c in self.w ])
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
1170379
def _set_unicode(self, value):
        
        values = list(self.unicodes)
        if value in values:
            values.remove(value)
        values.insert(0, value)
        self.unicodes = values
978353
def pack_unicode(cls, value, charset="utf-8", errors="strict"):
        
        assert isinstance(value, unicode)

        try:
            value = value.encode(charset, errors)
        except UnicodeEncodeError as e:
            raise InvalidData("Error encoding unicode value '%s': %s" % (repr(value), e))

        value_len_packed = cls.pack_int_base128(len(value))
        return struct.pack("<%ds%ds" % (len(value_len_packed), len(value)), value_len_packed,  value)
263084
def as_unicode(obj):
    
    if sys.version_info.major < 3 and isinstance(obj, str):
        obj = obj.decode('utf-8')
    return unicode(obj)
926133
def make_unicode(string):
    
    if sys.version < '3' and isinstance(string, str):
        return unicode(string.decode('utf-8'))

    return string
1281194
def to_unicode(string):
    """"""
    if not is_unicode(string):
        for codec in CODECS:
            try:
                unic = to_text_string(string, codec)
            except UnicodeError:
                pass
            except TypeError:
                break
            else:
                return unic
    return string
78856
def utf82unicode(value):
    
    try:
        return value.decode("utf8")
    except Exception as e:
        if not _Log:
            _late_import()

        if not is_binary(value):
            _Log.error("Can not convert {{type}} to unicode because it's not bytes",  type= type(value).__name__)

        e = _Except.wrap(e)
        for i, c in enumerate(value):
            try:
                c.decode("utf8")
            except Exception as f:
                _Log.error("Can not convert charcode {{c}} in string index {{i}}", i=i, c=ord(c), cause=[e, _Except.wrap(f)])

        try:
            latin1 = text_type(value.decode("latin1"))
            _Log.error("Can not explain conversion failure, but seems to be latin1", e)
        except Exception:
            pass

        try:
            a = text_type(value.decode("latin1"))
            _Log.error("Can not explain conversion failure, but seems to be latin1", e)
        except Exception:
            pass

        _Log.error("Can not explain conversion failure of " + type(value).__name__ + "!", e)
1063190
def get_unicode_str(obj):
    """"""
    if isinstance(obj, six.text_type):
        return obj
    if isinstance(obj, six.binary_type):
        return obj.decode("utf-8", errors="ignore")
    return six.text_type(obj)
128091
def force_unicode(value):
    
    if IS_PY3:
        # Python 3.X
        if isinstance(value, bytes):
            value = value.decode('utf-8', errors='replace')
        elif not isinstance(value, str):
            value = str(value)
    else:
        # Python 2.X
        if isinstance(value, str):
            value = value.decode('utf-8', 'replace')
        elif not isinstance(value, basestring):  # NOQA: F821
            value = unicode(value)  # NOQA: F821

    return value
204647
def evaluate_unicode(self, value):
        """"""

        if value.startswith('u8'):
            length = 1
            value = value[3:-1]
            encoding = 'utf-8'
        elif value.startswith('u'):
            length = 2
            value = value[2:-1]
            encoding = 'utf-16'
        else:
            length = 4
            value = value[2:-1]
            encoding = 'utf-32'

        def replace_unicode(m):
            """Replace Unicode."""

            groups = m.groupdict()
            esc = m.group(0)
            value = esc
            if groups.get('special'):
                # Handle basic string escapes.
                value = BACK_SLASH_TRANSLATION[esc]
            elif groups.get('char') or groups.get('oct'):
                # Handle character escapes.
                integer = int(esc[2:], 16) if groups.get('char') else int(esc[1:], 8)
                if (
                    (length < 2 and integer <= 0xFF) or
                    (length < 4 and integer <= 0xFFFF) or
                    (length >= 4 and integer <= 0x10FFFF)
                ):
                    try:
                        value = chr(integer)
                    except Exception:
                        value = ' '
            return value

        return self.norm_nl(RE_UESC.sub(replace_unicode, value).replace('\x00', '\n')), encoding
624315
def _ensure_unicode_string(string):
        
        if not isinstance(string, six.text_type):
            string = string.decode('utf-8')
        return string
492568
def safe_unicode(string):
    ''''''
    if not isinstance(string, basestring):
        string = unicode(string)
    if isinstance(string, unicode):
        string = string.encode('utf8')
    return string
217541
def encode(cls, value):
        
        coerced = unicode(value)
        if coerced == value:
            return coerced.encode(cls._encoding)

        raise InvalidValue('not text')