python类unicode()的实例源码

compat.py 文件源码 项目:Sudoku-Solver 作者: ayush1997 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
compat.py 文件源码 项目:GAMADV-X 作者: taers232c 项目源码 文件源码 阅读 54 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
compat.py 文件源码 项目:GAMADV-X 作者: taers232c 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
__init__.py 文件源码 项目:GAMADV-X 作者: taers232c 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
__init__.py 文件源码 项目:GAMADV-X 作者: taers232c 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
compat.py 文件源码 项目:enkiWS 作者: juliettef 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
compat.py 文件源码 项目:enkiWS 作者: juliettef 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
unicode.py 文件源码 项目:dotfiles 作者: gbraad 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def u(s):
    '''Return unicode instance assuming UTF-8 encoded string.
    '''
    if type(s) is unicode:
        return s
    else:
        return unicode(s, 'utf-8')
unicode.py 文件源码 项目:dotfiles 作者: gbraad 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def out_u(s):
    '''Return unicode string suitable for displaying

    Unlike other functions assumes get_preferred_output_encoding() first. Unlike 
    u() does not throw exceptions for invalid unicode strings. Unlike 
    safe_unicode() does throw an exception if object is not a string.
    '''
    if isinstance(s, unicode):
        return s
    elif isinstance(s, bytes):
        return unicode(s, get_preferred_output_encoding(), 'powerline_decode_error')
    else:
        raise TypeError('Expected unicode or bytes instance, got {0}'.format(repr(type(s))))
unicode.py 文件源码 项目:dotfiles 作者: gbraad 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def safe_unicode(s):
    '''Return unicode instance without raising an exception.

    Order of assumptions:
    * ASCII string or unicode object
    * UTF-8 string
    * Object with __str__() or __repr__() method that returns UTF-8 string or 
      unicode object (depending on python version)
    * String in powerline.lib.encoding.get_preferred_output_encoding() encoding
    * If everything failed use safe_unicode on last exception with which 
      everything failed
    '''
    try:
        try:
            if type(s) is bytes:
                return unicode(s, 'ascii')
            else:
                return unicode(s)
        except UnicodeDecodeError:
            try:
                return unicode(s, 'utf-8')
            except TypeError:
                return unicode(str(s), 'utf-8')
            except UnicodeDecodeError:
                return unicode(s, get_preferred_output_encoding())
    except Exception as e:
        return safe_unicode(e)
validator.py 文件源码 项目:request_validator 作者: amirasaran 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def check_string(self):
        if isinstance(self.data, (str, unicode)):
            return True
        if self.data is None:
            return True

        self.error = self._MESSAGES[self.STRING].format(data_type=type(self.data).__name__)
        return False
validator.py 文件源码 项目:request_validator 作者: amirasaran 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def check_date(self):
        if isinstance(self.data, (str, unicode)):
            self.data = self.data.strip()
        import datetime
        if self._value['convert_to_date']:
            if isinstance(self.data, datetime.datetime):
                self.data = self.data.date()
                return True
            elif isinstance(self.data, datetime.date):
                return True
            elif isinstance(self.data, (str, unicode)):
                try:
                    self.data = datetime.datetime.strptime(self.data, self._value['format']).date()
                    return True
                except Exception as e:
                    self.error = self._MESSAGES[self.DATE].format(date_format=self._value['format'],
                                                                  data=self.data)
                    return False
        else:
            if isinstance(self.data, datetime.datetime):
                self.data = self.data.date().strftime(self._value['format'])
                return True
            elif isinstance(self.data, datetime.date):
                self.data = self.data.strftime(self._value['format'])
                return True
            elif isinstance(self.data, (str, unicode)):
                try:
                    self.data = datetime.datetime.strptime(
                        self.data,
                        self._value['format']
                    ).date().strftime(self._value['format'])
                    return True
                except Exception as e:
                    self.error = self._MESSAGES[self.DATE].format(date_format=self._value['format'],
                                                                  data=self.data)
                    return False
        self.error = self._MESSAGES[self.DATE].format(date_format=self._value['format'], data=self.data)
        return False
compat.py 文件源码 项目:python-flask-security 作者: weinbergdavid 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
compat.py 文件源码 项目:python-flask-security 作者: weinbergdavid 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
py3compat.py 文件源码 项目:fortress 作者: rscircus 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def unicode(s):
  """Force conversion of s to unicode."""
  if PY3:
    return s
  else:
    return __builtin__.unicode(s, 'utf-8')


# In Python 3.2+, readfp is deprecated in favor of read_file, which doesn't
# exist in Python 2 yet. To avoid deprecation warnings, subclass ConfigParser to
# fix this - now read_file works across all Python versions we care about.
compat.py 文件源码 项目:GAMADV-XTD 作者: taers232c 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def print_(*args, **kwds):
        """The new-style print function."""
        # extract kwd args
        fp = kwds.pop("file", sys.stdout)
        sep = kwds.pop("sep", None)
        end = kwds.pop("end", None)
        if kwds:
            raise TypeError("invalid keyword arguments")

        # short-circuit if no target
        if fp is None:
            return

        # use unicode or bytes ?
        want_unicode = isinstance(sep, unicode) or isinstance(end, unicode) or \
                       any(isinstance(arg, unicode) for arg in args)

        # pick default end sequence
        if end is None:
            end = u("\n") if want_unicode else "\n"
        elif not isinstance(end, base_string_types):
            raise TypeError("end must be None or a string")

        # pick default separator
        if sep is None:
            sep = u(" ") if want_unicode else " "
        elif not isinstance(sep, base_string_types):
            raise TypeError("sep must be None or a string")

        # write to buffer
        first = True
        write = fp.write
        for arg in args:
            if first:
                first = False
            else:
                write(sep)
            if not isinstance(arg, basestring):
                arg = str(arg)
            write(arg)
        write(end)

#=============================================================================
# lazy overlay module
#=============================================================================
numerictypes.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def bitname(obj):
    """Return a bit-width name for a given type object"""
    name = obj.__name__
    base = ''
    char = ''
    try:
        if name[-1] == '_':
            newname = name[:-1]
        else:
            newname = name
        info = typeinfo[english_upper(newname)]
        assert(info[-1] == obj)  # sanity check
        bits = info[2]

    except KeyError:     # bit-width name
        base, bits = _evalname(name)
        char = base[0]

    if name == 'bool_':
        char = 'b'
        base = 'bool'
    elif name == 'void':
        char = 'V'
        base = 'void'
    elif name == 'object_':
        char = 'O'
        base = 'object'
        bits = 0
    elif name == 'datetime64':
        char = 'M'
    elif name == 'timedelta64':
        char = 'm'

    if sys.version_info[0] >= 3:
        if name == 'bytes_':
            char = 'S'
            base = 'bytes'
        elif name == 'str_':
            char = 'U'
            base = 'str'
    else:
        if name == 'string_':
            char = 'S'
            base = 'string'
        elif name == 'unicode_':
            char = 'U'
            base = 'unicode'

    bytes = bits // 8

    if char != '' and bytes != 0:
        char = "%s%d" % (char, bytes)

    return base, bits, char
numerictypes.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def _set_up_aliases():
    type_pairs = [('complex_', 'cdouble'),
                  ('int0', 'intp'),
                  ('uint0', 'uintp'),
                  ('single', 'float'),
                  ('csingle', 'cfloat'),
                  ('singlecomplex', 'cfloat'),
                  ('float_', 'double'),
                  ('intc', 'int'),
                  ('uintc', 'uint'),
                  ('int_', 'long'),
                  ('uint', 'ulong'),
                  ('cfloat', 'cdouble'),
                  ('longfloat', 'longdouble'),
                  ('clongfloat', 'clongdouble'),
                  ('longcomplex', 'clongdouble'),
                  ('bool_', 'bool'),
                  ('unicode_', 'unicode'),
                  ('object_', 'object')]
    if sys.version_info[0] >= 3:
        type_pairs.extend([('bytes_', 'string'),
                           ('str_', 'unicode'),
                           ('string_', 'string')])
    else:
        type_pairs.extend([('str_', 'string'),
                           ('string_', 'string'),
                           ('bytes_', 'string')])
    for alias, t in type_pairs:
        allTypes[alias] = allTypes[t]
        sctypeDict[alias] = sctypeDict[t]
    # Remove aliases overriding python types and modules
    to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float',
                 'complex', 'bool', 'string', 'datetime', 'timedelta']
    if sys.version_info[0] >= 3:
        # Py3K
        to_remove.append('bytes')
        to_remove.append('str')
        to_remove.remove('unicode')
        to_remove.remove('long')
    for t in to_remove:
        try:
            del allTypes[t]
            del sctypeDict[t]
        except KeyError:
            pass
numerictypes.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def bitname(obj):
    """Return a bit-width name for a given type object"""
    name = obj.__name__
    base = ''
    char = ''
    try:
        if name[-1] == '_':
            newname = name[:-1]
        else:
            newname = name
        info = typeinfo[english_upper(newname)]
        assert(info[-1] == obj)  # sanity check
        bits = info[2]

    except KeyError:     # bit-width name
        base, bits = _evalname(name)
        char = base[0]

    if name == 'bool_':
        char = 'b'
        base = 'bool'
    elif name == 'void':
        char = 'V'
        base = 'void'
    elif name == 'object_':
        char = 'O'
        base = 'object'
        bits = 0
    elif name == 'datetime64':
        char = 'M'
    elif name == 'timedelta64':
        char = 'm'

    if sys.version_info[0] >= 3:
        if name == 'bytes_':
            char = 'S'
            base = 'bytes'
        elif name == 'str_':
            char = 'U'
            base = 'str'
    else:
        if name == 'string_':
            char = 'S'
            base = 'string'
        elif name == 'unicode_':
            char = 'U'
            base = 'unicode'

    bytes = bits // 8

    if char != '' and bytes != 0:
        char = "%s%d" % (char, bytes)

    return base, bits, char
numerictypes.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _set_up_aliases():
    type_pairs = [('complex_', 'cdouble'),
                  ('int0', 'intp'),
                  ('uint0', 'uintp'),
                  ('single', 'float'),
                  ('csingle', 'cfloat'),
                  ('singlecomplex', 'cfloat'),
                  ('float_', 'double'),
                  ('intc', 'int'),
                  ('uintc', 'uint'),
                  ('int_', 'long'),
                  ('uint', 'ulong'),
                  ('cfloat', 'cdouble'),
                  ('longfloat', 'longdouble'),
                  ('clongfloat', 'clongdouble'),
                  ('longcomplex', 'clongdouble'),
                  ('bool_', 'bool'),
                  ('unicode_', 'unicode'),
                  ('object_', 'object')]
    if sys.version_info[0] >= 3:
        type_pairs.extend([('bytes_', 'string'),
                           ('str_', 'unicode'),
                           ('string_', 'string')])
    else:
        type_pairs.extend([('str_', 'string'),
                           ('string_', 'string'),
                           ('bytes_', 'string')])
    for alias, t in type_pairs:
        allTypes[alias] = allTypes[t]
        sctypeDict[alias] = sctypeDict[t]
    # Remove aliases overriding python types and modules
    to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float',
                 'complex', 'bool', 'string', 'datetime', 'timedelta']
    if sys.version_info[0] >= 3:
        # Py3K
        to_remove.append('bytes')
        to_remove.append('str')
        to_remove.remove('unicode')
        to_remove.remove('long')
    for t in to_remove:
        try:
            del allTypes[t]
            del sctypeDict[t]
        except KeyError:
            pass


问题


面经


文章

微信
公众号

扫码关注公众号