您的位置:首页 > 编程语言 > Python开发

Python一些很实用的知识

2012-06-10 21:59 513 查看

dict.pop(key[, default])

如果key在字典中,删除它并返回它的值,否则返回default。

如果default没有给出,并且key不在dict中,就会触发一个keyError错误

例如:

cache = kwargs.pop('cache', None)

**kwargs接收参数自动变成dict,这里如果里面有cache,就返回cache的值,如果没有返回None

[b]collections

[/b]
实现了一些特定的类型,用于替代python内置的dict,list,set,tuple

比如deque,是一个类似双向链表的容器,可以任一端进行append和pop

>>> from collections import deque
>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d:                   # iterate over the deque's elements
...     print elem.upper()
G
H
I

>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])



[b]re.sub(pattern, repl, string, count=0, flags=0)

[/b]

re.sub 函数进行以正则表达式为基础的替换工作
>>> import re
>>> re.search('[abc]', 'Mark') <_sre.SRE_Match object at 0x001C1FA8>
>>> re.sub('[abc]', 'o', 'Mark') 'Mork'
>>> re.sub('[abc]', 'o', 'rock') 'rook'
>>> re.sub('[abc]', 'o', 'caps') 'oops'
Mark 包含 a,b,或者 c吗?是的,含有 a。
好的,现在找出 a,b,或者 c 并以 o 取代之。Mark 就变成 Mork 了。
同一方法可以将 rock 变成 rook。
你可能认为它可以将 caps 变成 oaps,但事实并非如此。re.sub 替换所有 的匹配项,并不只是第一个匹配项。因此正则表达式将会把 caps 变成 oops,因为 c 和 a 都被转换为 o了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: