1.写函数,修改指定文件中的内容,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
def batch_edit(filename,old_contcnt,new_content):
import os
with open(filename,'r',encoding='utf-8') as read_f,open('.bak.swap','w',encoding='utf-8') as write_f:
for line in read_f:
if old_name in line:
line=line.replace(old_content,new_content)
write_f.write(line)
os.remove(filename)
os.rename('.bak.swap',filename)
batch_edit('D:\test.txt','aaa','bbb')
2.写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
def count_type(lst):
import string
digitl_count=0
alpha_count=0
space_count=0
other_count=0
for t in lst:
if t.isspace():
space_count+=1
elif t.isalpha():
alpha_count+=1
elif t.isdigit():
digitl_count+=1
else:
other_count+=1
print ('d_count=%s,a_count=%s,s_count=%s,other_count=%s'%(digitl_count,alpha_count,space_count,other_count))
count_type('fdafda 156456615 $%%')
3.写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def judgment(*args):
lst = input('>>>:',*args)
if len(lst) > 5:
print('object lenth > 5')
else:
print('object lenth <5')
judgment()
4.写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def judgment(lst):
if len(lst)> 2:
return lst[0:2]
else:
print('object lenth <5')
print(judgment([' ','shgs',43243]))
5.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
def fu(lst):
i=0
new_lst=[]
for lst[i] in lst:
if i%2 ==0:
pass
else:
new_lst.append(lst[i])
i+=1
print(new_lst)
fu(['adafd','a','111','123'])
6.写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表
def fuc(input):
dict={}
for key,item in input.items():
if len(item) > 2:
dict[key] = item[:2]
return dict
print(fuc({'u1':'123456','u2':'234567','u3':'345678'}))