python内置方法、模块讲解(三十一)

  • 2016-08-18 20:19:59
  • 1731
  • 0

七十八、unicode类

1、定义:

class unicode(basestring)
 |  unicode(object='') -> unicode object
 |  unicode(string[, encoding[, errors]]) -> unicode object
 |
 |  Create a new Unicode object from the given encoded string.
 |  encoding defaults to the current default string encoding.
 |  errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
 |
 |  Method resolution order:
 |      unicode
 |      basestring
 |      object

2、解释:将编码的字符串转为unicode对象,编码方式默认为当前的字符串编码

3、举例:

>>> a = "fdsafd"
>>> unicode(a)
u'fdsafd'
>>> a = "python博客"
>>> unicode(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb2 in position 6: ordinal not in range(128)
>>> unicode(a, 'gbk')
u'python\u535a\u5ba2'
由于存在中文, 而当前python环境默认编码为ascii, 因此需要指定解码方式(即当前编辑环境的编码)为gbk

七十九、vars方法

1、定义:

vars(...)
    vars([object]) -> dictionary

    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.

2、解释:若未传入参数,则相当于函数locals(见https://aoyanming.com/blog/display/27);如传入了参数object,则相当于调用object.__dict__,因为传入的object必须含有__dict__属性

3、举例:

>>> import datetime
>>> vars(datetime)
{'timedelta': <type 'datetime.timedelta'>, 'MAXYEAR': 9999, '__package__': None, 'date': <type 'datetime.date'>, 'datetime_CAPI': <capsule object "datetime.datetime_CAPI" at 0x0000000002B542A0>, 'tzinfo': <type 'datetime.tzinfo'>, 'time': <type 'datetime.time'>, 'MINYEAR': 1, '__name__': 'datetime', 'datetime': <type 'datetime.datetime'>, '__doc__': 'Fast implementation of the datetime type.'}
>>> datetime.__dict__
{'timedelta': <type 'datetime.timedelta'>, 'MAXYEAR': 9999, '__package__': None, 'date': <type 'datetime.date'>, 'datetime_CAPI': <capsule object "datetime.datetime_CAPI" at 0x0000000002B542A0>, 'tzinfo': <type 'datetime.tzinfo'>, 'time': <type 'datetime.time'>, 'MINYEAR': 1, '__name__': 'datetime', 'datetime': <type 'datetime.datetime'>, '__doc__': 'Fast implementation of the datetime type.'
 

 


发表评论

* *