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

  • 2016-08-18 20:20:43
  • 1492
  • 0

八十、xrange类

1、定义:

class xrange(object)
 |  xrange(stop) -> xrange object
 |  xrange(start, stop[, step]) -> xrange object
 |
 |  Like range(), but instead of returning a list, returns an object that
 |  generates the numbers in the range on demand.  For looping, this is
 |  slightly faster than range() and more memory efficient.

2、解释:该方法与range(详见http://aoyanming.com/blog/display/31)类似, 不同的是xrange按要求返回的是可以生成一段变化的数字的对象。迭代速度以及内存效率要比range更快、更高效。

3、举例:

>>> xrange(1, 10, 3)
xrange(1, 10, 3)
>>> xrange(10)
xrange(10)
>>> range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

八十一、zip方法

(以下省略)

阅读更多

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

  • 2016-08-18 20:19:59
  • 1476
  • 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方法

(以下省略)

阅读更多

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

  • 2016-07-23 22:47:03
  • 1331
  • 0

七十六、type类

1、定义:

class type(object)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type

2、解释:用于查看一个对象的类型(非常常用)或者创造一个新的类对象(可以理解成用于创造类对象(类也是对象)的元类)。

3、举例:

>>> type(1)
<type 'int'>
>>> type("a")
<type 'str'>
>>> type([])
<type 'list'>

>>> class A(object):
...     pass
...
>>> A
<class '__main__.A'>
>>> type('A', (), {})
<class '__main__.A'>

七十七、unichr方法

(以下省略)

阅读更多