2、寫函數,,用戶傳入修改的文件名,與要修改的內容,執行函數,完成整個文件的批量修改操作
1 # 方法一 2 # import os 3 # def fun(): #y為要修改的內容,z為修改的結果 4 # y=input("請輸入你要修改的內容:>>>") 5 # z=input("請輸入你想要修改后的內容:>>>") 6 # with open('a.txt','r',encoding='utf-8') as read_f,\ 7 # open('b.txt','w',encoding='utf-8') as write_f: 8 # data=read_f.read() 9 # write_f.write(data.replace(y,z)) 10 # os.remove('a.txt') 11 # os.rename('b.txt','a.txt') 12 # fun() 13 14 # 方法二 15 # import os 16 # def fun(old_content,new_content): #y為要修改的內容,z為修改的結果 17 # with open('a.txt','r',encoding='utf-8') as read_f,\ 18 # open('b.txt','w',encoding='utf-8') as write_f: 19 # for line in read_f: 20 # if old_content in line: 21 # write_f.write(line.replace(old_content, new_content)) 22 # os.remove('a.txt') 23 # os.rename('b.txt','a.txt') 24 # fun('alex','xx')
# 3、寫函數,檢查用戶傳入的對象(字符串、列表、元組)的每一個元素是否含有空內容。

1 def check(o): 2 if o:#就相當於bool(o)==True, #判斷o的布爾值,如果不為空就執行子代碼塊的內容 3 if type(o) is str: 4 for i in o: 5 if i==' ': 6 return True 7 else: 8 for i in o: 9 if not i : 10 return True 11 else: 12 return True 13 print(check('fh fh ')) 14 print(check(['',11,22,' fdg ']))
4、寫函數,檢查傳入字典的每一個value的長度, 如果大於2,那么僅保留前兩個長度的內容,
並將新內容返回給調用者。

1 # 方法一 2 # def fun(d): 3 # for i,v in d.items(): 4 # if len(v)>2: 5 # d[i]=v[0:2] 6 # return d 7 # dic = {"k1": "v1v1", "k2": [11, 22, 33, 44]} 8 # f=fun(dic) 9 # print(f) 10 11 12 # 方法二 13 # def fun(d): 14 # for key in d: 15 # if len(d[key])>2: 16 # d[key]=d[key][0:2] 17 # return d 18 # dic = {"k1": "v1v1", "k2": [11, 22, 33, 44]} 19 # f=fun(dic) 20 # print(f)