python_day3

01、编码

import sys
print(sys.getdefaultencoding())

s = "你哈"
s_gbk = s.encode("gbk")

print(s_gbk)
print(s.encode())

gbk_to_utf8 = s_gbk.decode("gbk").encode("utf-8")
print("utf8",gbk_to_utf8)

02、文件修改

 1 import sys
 2 f = open("yesterday2","r",encoding="utf-8")
 3 f_new = open("yesterday2.bak","w",encoding="utf-8")
 4 
 5 find_str = sys.argv[1]
 6 replace_str = sys.argv[2]
 7 for line in f:
 8     if find_str in line:
 9         line = line.replace(find_str,replace_str)
10     f_new.write(line)
11 f.close()
12 f_new.close()

03、高阶函数

def add(a,b,f):
    return f(a)+f(b)

res = add(3,-6,abs)
print(res)

04、递归

def calc(n):
    print(n)
    if int(n/2) >0:
        return calc( int(n/2) )
    print("->",n)
    
calc(10)

05、进度条

import sys,time

for i in range(20):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.1)

06、集合

 1 list_1 = [1,4,5,7,3,6,7,9]
 2 list_1 = set(list_1)
 3 
 4 list_2 =set([2,6,0,66,22,8,4])
 5 print(list_1,list_2)
 6 '''
 7 #交集
 8 print(  list_1.intersection(list_2) )
 9 
10 #并集
11 print(list_1.union(list_2))
12 
13 #差集 in list_1 but not in list_2
14 print(list_1.difference(list_2))
15 print(list_2.difference(list_1))
16 
17 #子集
18 list_3 = set([1,3,7])
19 print(list_3.issubset(list_1))
20 print(list_1.issuperset(list_3))
21 
22 #对称差集
23 print(list_1.symmetric_difference(list_2))
24 
25 print("-------------")
26 
27 list_4 = set([5,6,7,8])
28 print(list_3.isdisjoint(list_4)) # Return True if two sets have a null intersection.
29 '''
30 
31 
32 #交集
33 print(list_1 & list_2)
34 #union
35 print(list_2 | list_1)
36 
37 #difference
38 print(list_1 - list_2) # in list 1 but not in list 2
39 
40 #对称差集
41 print(list_1 ^ list_2)
42 
43 list_1.add(999)
44 list_1.update([888,777,555])
45 print(list_1)
46 
47 print(list_1.pop())
48 print(list_1.pop())
49 print(list_1.pop())
50 print(list_1.pop())
51 
52 print(  list_1.discard(888)  )

07、with语句

import sys
#f = open("yesterday2","r",encoding="utf-8")

with open("yesterday2","r",encoding="utf-8") as f ,
      open("yesterday2", "r", encoding="utf-8") as f2:
    for line in f:
        print(line)

08、字符串

 1 name = "my 	name is {name} and i am {year} old"
 2 
 3 print(name.capitalize())
 4 print(name.count("a"))
 5 print(name.center(50,"-"))
 6 print(name.endswith("ex"))
 7 print(name.expandtabs(tabsize=30))
 8 print(name[name.find("name"):])
 9 print(name.format(name='alex',year=23))
10 print(name.format_map(  {'name':'alex','year':12}  ))
11 print('ab23'.isalnum())
12 print('abA'.isalpha())
13 print('1A'.isdecimal())
14 print('1A'.isdigit())
15 print('a 1A'.isidentifier()) #判读是不是一个合法的标识符
16 print('33A'.isnumeric())
17 print('My Name Is  '.istitle())
18 print('My Name Is  '.isprintable()) #tty file ,drive file
19 print('My Name Is  '.isupper())
20 print('+'.join( ['1','2','3'])  )
21 print( name.ljust(50,'*')  )
22 print( name.rjust(50,'-')  )
23 print( 'Alex'.lower()  )
24 print( 'Alex'.upper()  )
25 print( '
Alex'.lstrip()  )
26 print( 'Alex
'.rstrip()  )
27 print( '    Alex
'.strip()  )
28 p = str.maketrans("abcdefli",'123$@456')
29 print("alex li".translate(p) )
30 
31 print('alex li'.replace('l','L',1))
32 print('alex lil'.rfind('l'))
33 print('1+2+3+4'.split('
'))
34 print('1+2
+3+4'.splitlines())
35 print('Alex Li'.swapcase())
36 print('lex li'.title())
37 print('lex li'.zfill(50))
38 
39 print( '---')

08、文件

 1 #data = open("yesterday",encoding="utf-8").read()
 2 f = open("yesterday2",'a',encoding="utf-8") #文件句柄
 3 #a = append 追加
 4 
 5 f.write("
when i was young i listen to the radio
")
 6 data = f.read()
 7 print('--read',data)
 8 f.close()
 9 
10 
11 #f = open("yesterday2",'r+',encoding="utf-8") #文件句柄 读写
12 #f = open("yesterday2",'w+',encoding="utf-8") #文件句柄 写读
13 #f = open("yesterday2",'a+',encoding="utf-8") #文件句柄 追加读写
14 f = open("yesterday2",'wb') #文件句柄  二进制文件
15 f.write("hello binary
".encode())
16 f.close()
17 
18 print(f.encoding)
19 
20 #print(f.flush())
21 print(dir(f.buffer) )
22 #high bige
23 
24 count = 0
25 for line in f:
26     if count == 9:
27         print('----我是分割线----------')
28         count += 1
29         continue
30     print(line)
31     count +=1
32 
33 #low loop
34 
35 for index,line in enumerate(f.readlines()):
36     if index == 9:
37         print('----我是分割线----------')
38         continue
39     print(line.strip())
40 #for i in range(5):
41 #    print(f.readline())

09、函数操作

 1 import  time
 2 def logger():
 3     time_format = '%Y-%m-%d %X'
 4     time_current = time.strftime(time_format)
 5     with open('a.txt','a+') as f:
 6         f.write('%s end action
' %time_current)
 7 
 8 def test1():
 9     print('in the test1')
10 
11     logger()
12 def test2():
13     print('in the test2')
14 
15     logger()
16 def test3():
17     print('in the test3')
18     logger()
19 
20 test1()
21 test2()
22 test3()

10、函数一

 1 #*args:接受N个位置参数,转换成元组形式
 2 # def test(*args):
 3 #     print(args)
 4 #
 5 # test(1,2,3,4,5,5)
 6 # test(*[1,2,4,5,5])#  args=tuple([1,2,3,4,5])
 7 
 8 # def test1(x,*args):
 9 #     print(x)
10 #     print(args)
11 #
12 # test1(1,2,3,4,5,6,7)
13 
14 
15 #**kwargs:接受N个关键字参数,转换成字典的方式
16 # def test2(**kwargs):
17 #     print(kwargs)
18 #     print(kwargs['name'])
19 #     print(kwargs['age'])
20 #     print(kwargs['sex'])
21 #
22 # test2(name='alex',age=8,sex='F')
23 # test2(**{'name':'alex','age':8})
24 # def test3(name,**kwargs):
25 #     print(name)
26 #     print(kwargs)
27 #
28 # test3('alex',age=18,sex='m')
29 
30 # def test4(name,age=18,**kwargs):
31 #     print(name)
32 #     print(age)
33 #     print(kwargs)
34 #
35 # test4('alex',age=34,sex='m',hobby='tesla')
36 
37 def test4(name,age=18,*args,**kwargs):
38     print(name)
39     print(age)
40     print(args)
41     print(kwargs)
42     logger("TEST4")
43 
44 
45 
46 def logger(source):
47     print("from %s" %  source)
48 
49 test4('alex',age=34,sex='m',hobby='tesla')
原文地址:https://www.cnblogs.com/xieyi-1994/p/11623752.html