标签:添加 pop get file map color efault 默认 序列
>>> f="hi,%a is a %a" #%后面只能跟同一个值 >>> v=(‘mac‘,‘dog‘) >>> f % v #最原始 "hi,‘mac‘ is a ‘dog‘" >>> from string import Template >>> tmp=Template(‘hi, $who is a $what‘)#引用模块 >>> tmp.substitute(who=‘mac‘,what=‘dog‘) ‘hi, mac is a dog‘ >>> "hi,{} is a {}".format(‘mac‘,‘dog‘)#使用默认顺序 ‘hi,mac is a dog‘ >>> "hi,{1} is a {0}".format(‘mac‘,‘dog‘)#索引 ‘hi,dog is a mac‘ >>> "hi,{name} is a {what}".format(name=‘mac‘,what=‘dog‘)#制定名称 ‘hi,mac is a dog‘ >>> names=[‘aaa‘,‘bbbb‘] >>> ‘hi,{name[0]} is a dog‘.format(name=names)#可传序列 ‘hi,aaa is a dog‘ >>> ‘{num:f}‘.format(num=100)#指定转换格式(值:格式) ‘100.000000‘ >>> ‘name‘.center(6) #指定(6)长度,使nameu居中 ‘ name ‘ >>> ‘name‘.find(‘am‘)#返回第一个的索引,没有返回-1 1 >>> ‘name‘.find(‘aaaa‘) -1 >>> ‘hi,name is a dog‘.find(‘is‘,2,100)#find(‘搜索值‘,开始索引,结束索引) 8 >>> ‘+‘.join([‘1‘,‘2‘,‘3‘])# join ‘1+2+3‘ >>> ‘AAA‘.lower()#小写 ‘aaa‘ >>> ‘name‘.replace(‘am‘,‘aaaaa‘)#替换 ‘naaaaae‘ >>> "nanenanenrnr".split(‘n‘)#分解 [‘‘, ‘a‘, ‘e‘, ‘a‘, ‘e‘, ‘r‘, ‘r‘] >>> ‘ name ‘.strip()#去除前后空格 ‘name‘ >>> ‘ ! **na!m*e !! ***‘.strip(‘*!‘)#去除指定字符 ‘ ! **na!m*e !! ‘ >>> dic={‘a‘:1,‘b‘:2,‘c‘:3}#创建字典 1 >>> dic[‘c‘] 3 >>> items=[(‘name‘,‘张三‘),(‘age‘,42)]#创建字典 2 >>> d=dict(items) >>> d {‘name‘: ‘张三‘, ‘age‘: 42} >>> d=dict(name=‘张三‘,age=31)#创建字典 3 >>> d {‘name‘: ‘张三‘, ‘age‘: 31} >>> book={‘a‘:12,‘b‘:111,‘c‘:333} >>> book {‘a‘: 12, ‘b‘: 111, ‘c‘: 333} >>> ‘a is {a}‘.format(a=‘fdssf‘) ‘a is fdssf‘ >>> ‘a is {a}‘.format_map(book)#字符转格式format_map ‘a is 12‘ >>> dict.fromkeys(‘name‘,‘age‘) #创建字典fromkeys {‘n‘: ‘age‘, ‘a‘: ‘age‘, ‘m‘: ‘age‘, ‘e‘: ‘age‘} >>> dict.fromkeys([‘name‘,‘age‘]) {‘name‘: None, ‘age‘: None} >>> dict.fromkeys([‘name‘,‘age‘],‘unknow‘)#设置默认值 {‘name‘: ‘unknow‘, ‘age‘: ‘unknow‘} >>> {‘a‘: 1, ‘b‘: 2, ‘c‘: 3} >>> dic.get(‘b‘) #get获取值,不报错,没有的话返回None。第二个参数可设置默认值 2 >>> dic {‘a‘: 1, ‘b‘: 2, ‘c‘: 3} >>> dic.pop() #必须有key参数 Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> dic.pop() TypeError: pop expected at least 1 arguments, got 0 >>> dic.popitem() #随机弹出并删除 (‘c‘, 3) >>> dic {‘a‘: 1, ‘b‘: 2} >>> dic {‘a‘: 1, ‘b‘: 2} >>> dic.setdefault(‘c‘,1111)#获取key为c的值,如果没有的c,就添加k=1 v=1111的元素,1111为可选参数,不填默认为None 1111 >>> dic {‘a‘: 1, ‘b‘: 2, ‘c‘: 1111} >>> dic.setdefault(‘c‘,222)#如果已经有k为c的值了,222将无意义。 1111 >>> dic {‘a‘: 1, ‘b‘: 2, ‘c‘: 1111} >>> >>> dic {‘a‘: 1, ‘b‘: 2, ‘c‘: 1111} >>> dd=dict.fromkeys([‘dd‘,‘ee‘],2222) >>> dd {‘dd‘: 2222, ‘ee‘: 2222} >>> dd[‘a‘]=1111 >>> dd {‘dd‘: 2222, ‘ee‘: 2222, ‘a‘: 1111} >>> dic.update(dd)#对于通过参数提供的字典,将其项添加到当前字典中。如果当前字典包含键相同的项,就替换它。 >>> dic {‘a‘: 1111, ‘b‘: 2, ‘c‘: 1111, ‘dd‘: 2222, ‘ee‘: 2222} >>>
标签:添加 pop get file map color efault 默认 序列
原文地址:https://www.cnblogs.com/wwz-wwz/p/11124052.html