pyhon第十四天作业
1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
def user(name):
import os
content = input('请输入要修改的内容:')
end_content = input('请输入修改之后的内容:')
if os.path.exists(name):
with open(name,'rb') as rf,\
open('.name.txt.swap','wb') as wf:
while True:
res = rf.readline().decode('utf-8')
if content in res:
i = res.replace(content, end_content)
wf.write(i.encode('utf-8'))
else:
wf.write(res.encode('utf-8'))
if len(res) == 0:
break
os.remove(name)
os.rename('.name.txt.swap',name)
print('修改完成')
else:
return '文件不存在'
path_file = input('请输入您的文件地址:>>')
user(path_file)
2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
def counts_func(*args):
number = 0
letter = 0
spc = 0
other = 0
for i in args:
if i.isdigit():
number +=1
elif i.isalpha():
letter +=1
elif i.isspace():
spc +=1
else:
other +=1
print('【数字】:{}个\n【字母】:{}个\n【空格】:{}个\n【其他】:{}个'.format(number,letter,spc,other))
res = input('写入内容:>>')
counts_func(*res)
3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def len_func(name):
if len(name) > 5:
return True
return False
str = 'sadn'
print(str,len_func(str))
l = [111,1221,1231,51,2,12,5,1]
print(l,len_func(l))
tuq = (1,2,45,[1234,1239,'dasuidh'])
print(tuq,len_func(tuq))
4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def list_func(list):
l = []
while True:
for list_num in list:
if len(l) < 2:
print(list_num)
l.append(list_num)
else:
break
break
return l
a = ['asd','fudhf',3,4,5,6]
print(list_func(a))
5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
def list_new_func(*args):
l = []
for i in args:
if args.index(i) % 2 ==1:
l.append(i)
return l
l = ['dasd','asdsa','123','ads3d',5,9]
print(list_new_func(*l))
t = ('dasd','asdsa','123','ads3d',5,9)
print(list_new_func(*t))
6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表
def func(**kwargs):
print(kwargs)
d = {}
for k in kwargs.keys():
v = kwargs.get(k)
if len(v) > 2:
res = v[0:2]
d[k] = res
return d
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
print(func(**dic))