python 笔记

来源:互联网 发布:淘宝怎么买原味丝袜 编辑:程序博客网 时间:2024/06/03 19:27
.>>> str1='i am a dashuaige'>>> str1[:5]'i am '>>> str1[:4]'i am'>>> str1[3]'m'>>> str2=str1[:5]+'haha'+str1[5:]>>> str2'i am hahaa dashuaige'>>> str2='xiaoche'>>> str2'xiaoche'>>> str2.capitalize ()'Xiaoche'>>> str3='XXXXXX'>>> str3.casefold ()'xxxxxx'>>> str3'XXXXXX'>>> str2'xiaoche'>>> str2.center (10)' xiaoche  '>>> str2.count (ch)Traceback (most recent call last):  File "<pyshell#14>", line 1, in <module>    str2.count (ch)NameError: name 'ch' is not defined>>> str2.count ('ch')1>>> str2.count ('ch',[0,3])Traceback (most recent call last):  File "<pyshell#16>", line 1, in <module>    str2.count ('ch',[0,3])TypeError: slice indices must be integers or None or have an __index__ method>>> str2.count ('ch',[0,[3]])Traceback (most recent call last):  File "<pyshell#17>", line 1, in <module>    str2.count ('ch',[0,[3]])TypeError: slice indices must be integers or None or have an __index__ method>>> str2.count ('ch',[,0[,3]])SyntaxError: invalid syntax>>> str2.count ('ch'[,0[,3]])SyntaxError: invalid syntax>>> str2.count ('ch',0,3)0>>> str2'xiaoche'>>> str2.endswith (che)Traceback (most recent call last):  File "<pyshell#22>", line 1, in <module>    str2.endswith (che)NameError: name 'che' is not defined>>> str2.endswith ('che')True>>> str2'xiaoche'>>> str2.expandtabs ()'xiaoche'>>> str3='X X X X'>>> str3.expandtabs ()'X X X X'>>> str3='X\tX\tX\tX\tX'>>> str3'X\tX\tX\tX\tX'>>> str3.expandtabs ()'X       X       X       X       X'>>> str3.find(X)Traceback (most recent call last):  File "<pyshell#31>", line 1, in <module>    str3.find(X)NameError: name 'X' is not defined>>> str3.find('X')0>>> str3='avaavavags'>>> str3.split('a')['', 'v', '', 'v', 'v', 'gs']>>> str3.swapcase()'AVAAVAVAGS'>>> str3'avaavavags'>>> str3.translate(str.maketrans('a','b'))'bvbbvbvbgs'>>> 





格式化的一部分知识

>>> '{0} love {1}.{2}'.format('wo','shi','wwoo')'wo love shi.wwoo'>>> '{a} love {b}.{c}'.format(a='wo',b='shi',c='wwoo')'wo love shi.wwoo'>>> '{0} love {b}.{c}'.format('wo',b='shi',c='wwoo')'wo love shi.wwoo'>>> '{a} love {b}.{2}'.format(a='wo',b='shi',c='wwoo')Traceback (most recent call last):  File "<pyshell#3>", line 1, in <module>    '{a} love {b}.{2}'.format(a='wo',b='shi',c='wwoo')IndexError: tuple index out of range

这里注意混用时数字要在字母前面,否则会报错

>>> '{0:.1f}{1}'.format (27.658,'gg')'27.7gg'
    当转义字符时

>>> '{{0}}'.format('haha')'{0}'>>> print('\ta')a>>> print('\\')\

字符串格式化符号含义及转义字符含义

这里有一个网站整理的不错http://bbs.fishc.com/

>>> '%c %c %c'5(97,98,99)#多个参数时用元组将其括起来SyntaxError: invalid syntax>>> '%c %c %c'%(97,98,99)#多个参数时用元组将其括起来'a b c'>>> '%c, %c, %c'%(97,98,99)#多个参数时用元组将其括起来'a, b, c'>>> '%s'%('wo wo ni ni ')'wo wo ni ni '>>> '%d+%d=%d'%(4,5,4+5)'4+5=9'>>> '%o'%10'12'>>> '%o'%10          #将10转化成八进制数'12'>>> '%x'%10           #格式化无符号十六进制数'a'>>> '%X'%10'A'>>> '%f'%22.222'22.222000'>>> '%.2f'%22.222'22.22'>>> #'%f'格式化定点数、可指定小数点后的精度>>> '%e'%^22.222      #用科学计数法格式化定点数SyntaxError: invalid syntax>>> '%e'%22.222'2.222200e+01'>>> '%g'%22.222'22.222'>>> #'%g'根据值得大小决定使用%f或%e>>> '%5.2f'%22.2222'22.22'>>> '%.2e'%22.222'2.22e+01'>>> '%10d'%2    #说明这个字符占十个空格'         2'>>> '%-10d'%2    #说明这个字符占十个空格,并且左对齐'2         '>>> '%+10d'%222.22    #说明这个字符占十个空格,显示+号'      +222'>>> '%+10d'%-222.22    #说明这个字符占十个空格,显示+号'      -222'>>> '%#o'%10   #前面带一个0o表示是一个八进制数'0o12'>>> '%#d'%10'10'>>> '%#x'%10'0xa'>>> '%#b'%10Traceback (most recent call last):  File "<pyshell#37>", line 1, in <module>    '%#b'%10ValueError: unsupported format character 'b' (0x62) at index 2>>> '%010d'%5'0000000005'>>> '%-010d'%5'5         '>>> '%00d'%5'5'>>> '%05d'%5'00005'


有关于列表的一些操作

>>> a=list()>>> a[]>>> b='wowo haha in n'>>> b=list(b)>>> b['w', 'o', 'w', 'o', ' ', 'h', 'a', 'h', 'a', ' ', 'i', 'n', ' ', 'n']>>> c=(1,2,3,4,5,6,7)>>> c=list(c)>>> c[1, 2, 3, 4, 5, 6, 7]>>> len(c)7>>> max(c)7>>> max(b)'w'>>> min(c)1

>>> c.append ('a')>>> c[1, 2, 3, 4, 5, 6, 7, 'a']>>> max(c)Traceback (most recent call last):  File "<pyshell#18>", line 1, in <module>    max(c)TypeError: '>' not supported between instances of 'str' and 'int'

求和
>>> tuple1=(1.1,2.2,3.3,4.4)>>> sum(tuple1)11.0>>> c[1, 2, 3, 4, 5, 6, 7, 'a']>>> sum(c)Traceback (most recent call last):  File "<pyshell#22>", line 1, in <module>    sum(c)TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>> c=[1,2,3,4,5,6,7,8,9,0]>>> len(c)10>>> sum(c)45>>> sum(c,10)55

排序
>>> a=[1,4,0,3.4,5.6,2.1]>>> sorted(a)[0, 1, 2.1, 3.4, 4, 5.6]


反转
>>> a[1, 4, 0, 3.4, 5.6, 2.1]>>> reversed(a)<list_reverseiterator object at 0x0000008EA66C5B70>>>> list(reversed(a))[2.1, 5.6, 3.4, 0, 4, 1]

枚举
>>> a=[1,4,0,3.4,5.6,2.1]>>> enumerate(a)<enumerate object at 0x0000008EA66EB678>>>> list(enumerate(a))[(0, 1), (1, 4), (2, 0), (3, 3.4), (4, 5.6), (5, 2.1)]

压缩
>>> a[1, 4, 0, 3.4, 5.6, 2.1]>>> b=[3,45,56,223,565]>>> b[3, 45, 56, 223, 565]>>> zip(a,b)<zip object at 0x0000008EA66AE988>>>> list(zip(a,b))[(1, 3), (4, 45), (0, 56), (3.4, 223), (5.6, 565)]

函数




  语法




>>> def SaySome(name,words):print(name+' haha '+words)>>> SaySome('baba','mama')baba haha mama>>> SaySome('mama','baba')mama haha baba>>> SaySome(words='mama',name='baba')baba haha mama

>>> def test(*parame):print('参数的长度是:',len(parame));print('第二个参数是:',parame[1]);>>> test(1,'jjjjja',3,4.5555,6778,3343)参数的长度是: 6第二个参数是: jjjjja>>> def test(*parame,exp):print('参数的长度是:',len(parame),exp);print('第二个参数是:',parame[1]);
>>> test(1,'jjjjja',3,4.5555,6778,3343)Traceback (most recent call last):  File "<pyshell#17>", line 1, in <module>    test(1,'jjjjja',3,4.5555,6778,3343)TypeError: test() missing 1 required keyword-only argument: 'exp'>>> test(1,'jjjjja',3,4.5555,6778,3343,exp=8)参数的长度是: 6 8第二个参数是: jjjjja


函数中对全局变量的修改往往不能生效

补充:



>>> count=10
>>> def test():count=100print(count)>>> test()100>>> print(count)10

>>> count=10>>> print(count)10>>> def test():global countcount=100print(count)>>> test()100>>> print(count)100

函数的嵌套

>>> def fun1():print('fun1正在被调用。。。。')def fun2():print('fun2正在被调用、、、')fun2()>>> fun1()fun1正在被调用。。。。fun2正在被调用、、、>>> fun2()Traceback (most recent call last):  File "<pyshell#33>", line 1, in <module>    fun2()NameError: name 'fun2' is not defined

闭包

>>> def funx(x):def funy(y):return x*yreturn funy>>> i=funx(8)>>> i<function funx.<locals>.funy at 0x0000008E84C8AD08>>>> type(i)<class 'function'>>>> i(5)40>>> type(i(5))<class 'int'>>>> funx(3)(4)12>>> funy(4)Traceback (most recent call last):  File "<pyshell#46>", line 1, in <module>    funy(4)NameError: name 'funy' is not defined

下面两个函数fun2调用时加上和不加上()区别特别大、、、、、
>>> def fun1():x=5def fun2():x*=xreturn xreturn fun2>>> fun1()<function fun1.<locals>.fun2 at 0x0000008E84C8ABF8>

>>> def fun1():x=5def fun2():x*=xreturn xreturn fun2()>>> fun1()Traceback (most recent call last):  File "<pyshell#63>", line 1, in <module>    fun1()  File "<pyshell#62>", line 6, in fun1    return fun2()  File "<pyshell#62>", line 4, in fun2    x*=xUnboundLocalError: local variable 'x' referenced before assignment
用列表的方法解决或nonlocal
>>> def fun1():x=[5]def fun2():x[0]*=x[0]return x[0]return fun2()>>> fun1()25

>>> def fun1():x=5def fun2():nonlocal x       #强制声明x不是局部变量x*=xreturn xreturn fun2()>>> fun1()25>>> xTraceback (most recent call last):  File "<pyshell#71>", line 1, in <module>    xNameError: name 'x' is not defined

Lambda匿名函数

>>> #匿名函数>>> def ds(x):return 2*x+1>>> ds(5)11>>> lambda x:2*x+1<function <lambda> at 0x000000133401C488>>>> g=lambda x:2*x+1>>> type(g)<class 'function'>>>> g(5)11>>> def add(x,y):return x+y>>> add(2,5)7>>> g=lambda x,y:x+y>>> g(2,5)7


Filter函数


Filter函数返回真值,滤除掉非真值的部分
>>> filter(None,[1,0,False,True])<filter object at 0x0000001334015A90>>>> list(filter(None,[1,0,False,True]))[1, True]
但是Filter函数应注意:filter(function or None, iterable) --> filter object
               使用时要么     filter(None,[1,0,False,True])
               要么   list(filter(lambda x:x%2,range(10)))
>>> def odd(x):return x%2>>> temp=range(10)>>> list(filter(odd,temp))[1, 3, 5, 7, 9]

>>> list(filter(lambda x:x%2,range(10)))[1, 3, 5, 7, 9]

字典的使用

>>> #字典,特点是大括号>>> dict1={'李宁':'一切皆有可能','耐克':'just do it','阿迪达斯':'impossible is nothing'}SyntaxError: invalid character in identifier>>> dict1={'李宁':'一切皆有可能','耐克';'just do it','阿迪达斯':'impossible is nothing'}SyntaxError: invalid syntax>>> dict1={'李宁':'一切皆有可能','耐克':'just do it','阿迪达斯':'impossible is nothing'}>>> print('阿迪达斯的口号是:',dict1['阿迪达斯'])阿迪达斯的口号是: impossible is nothing>>> dict2={'1':'come','2':'home'}>>> print('dict2[1]')dict2[1]>>> print(dict2[1])Traceback (most recent call last):  File "<pyshell#7>", line 1, in <module>    print(dict2[1])KeyError: 1>>> print(dict2['1'])come
>>> #dict3  创建一个字典
>>> dict3=dict((('a',1),('b',2),('c',3),('d',4)))>>> dict3{'a': 1, 'b': 2, 'c': 3, 'd': 4}>>> #使用=创建一个字典,key不能用引号>>> dict4=dict{爸爸='baba',mama='妈妈'}SyntaxError: invalid syntax>>> dict4=dict(爸爸='baba',mama='妈妈')>>> dict4{'爸爸': 'baba', 'mama': '妈妈'}>>> #key的修改>>> dict4['mama']='ma妈'>>> dict4{'爸爸': 'baba', 'mama': 'ma妈'}>>> #给字典添加一个key>>> dict4['爱迪生']='天才'>>> dict4{'爸爸': 'baba', 'mama': 'ma妈', '爱迪生': '天才'}





原创粉丝点击