python 基础教程之字符串字典

来源:互联网 发布:五笔拆字软件 编辑:程序博客网 时间:2024/06/07 15:25

字符串:


格式化

字符串格式化使用字符串格式化操作符%实现(%还用作模运算)

msg = 'hello! %s and %s'name = ('Ye ping','Xue xiaoyu') #元组print msg % name

模板字符串

替换单词

from string import Templates = Template('$x,glorious $x!')msg = s.substitute(x = 'slurm')print msg       # 结果为:slurm,glorious slurm

替换单词的一部分

s = Template("It's ${x}tastic!") #替换部分msg = s.substitute(x = 'slurm')print msg     
还可以使用字典

s = Template('A $thing must never $action.')d = {} #字典d['thing'] = 'gentleman'd['action'] = ''msg = s.substitute(d)print msg      # 结果为:A gentleman must never show his socks.

字符串方法

find

从字符串中查找子字符串,返回最左端索引,未找到返回-1

title = "Monty Python's Flying Circus"title.find(Monty)     #返回0

还可以选择起始点

s.find(str,1)              #提供起点s.find(str,1,18)            #提供起点,终点

join

是split的逆方法,很重要的方法

s = ['1', '2', '3', '4', '5']s = '+'.join(s)print s        # s = '1+2+3+4+5'

lower

返回小写

replace

匹配的字符串均被替换

'this is a test'.replace('is','eez')  #输出 theez eez a test

split

是join的逆方法

'1+2+3+4+5'.split('+')    # 输出['1', '2', '3', '4', '5']

strip

默认去除两侧的空格,不包括内部,也可以去除指定字符

translate

和replace一样,但是只能处理单字符,效率更高,使用前需完成转换表

from string import maketranstable = maketrans('cs','kz')'this is a test'.translate(table)  # thiz iz a tezt


translate(table,' ') 还有第二个参数,用来指定要删除的字符

字典

字典也称为映射(mapping),是 键:值 对的集合

构造如下:

dict = {'a':1, 'b':2, 'c':3}

基本操作:

len(dict)       #返回字典中项的数量dict['a']       #返回1,即对应的键值dict['a'] = 11  #修改键值del dict['a']   #删除键为‘a’的项‘k’ in dict     #检测是否存在键值为‘k’的项

格式化字符串:

phonebook = {'beth':'1111', 'alice':'2222', 'tom':'3333'}print "Tom's phone number is %(tom)s." % phonebook         #输出结果 Tom's phone number is 3333.

字典方法:

clear

清空字典,返回None

copy

复制一个新的副本,但这是个浅复制,替换值时不受影响,修改值则会受到影响

x = {'username':'admin','tes':['foo', 'bar', 'baz']}y = x.copy()y['username'] = 'root'y['tes'].remove('baz')print x                    # x = {'username': 'admin', 'tes': ['foo', 'bar']}print y                    # y = {'username': 'root', 'tes': ['foo', 'bar']}

避免这种问题,可以采用:

deepcopy

深复制函数

fromkeys

给新建的键建立字典,键值为None

new = {}list = ['name','age']new.fromkeys(list)print new             # new = {'age': None, 'name': None}#也可以自己提供默认值new.fromkeys(list,'defualt')print new            # new = {'age': 'defualt', 'name': 'defualt'}

get

访问字典的方法,类似dict[K]

但是不会报错

dict = {}print dict['k']        # 报错 ,KeyErrorprint dict.get('k')    # None

has_key

判断字典中是否有给给定的键

dict = {'a':1, 'b':2}dict.has_key('a')        # Truedict.has_key('c')        #False

items 和 iteritems

items 方法将所有字典项已列表方式返回

[(k,v),(k,v),...,(k,v)]

dict = {'a':1, 'b':2}it = dict.items()print it             # 结果 [('a', 1), ('b', 2)]

iteritems返回一个迭代器,更高效

keys 和 iterkeys

类似于items,只是将建返回

values 和 itervalues

同上类似

pop

移除给定键值的项

popitem

随机移除一项,因为字典没有顺序

setdefault

setdefault(Key,Values)

若果key存在,则修改Values,如果不存在,就加入

update

更新,相当与扩展,类似列表中的expend,若有相同项则覆盖

0 0
原创粉丝点击