PYTHON-DAY10-函数的定义与调用,返回值,和参数作业

# day10函数的定义调用和参数作业
# 1、写函数,用户传入修改的文件名、与要修改的内容,执行函数,完成批量修改操作
# def modify_file(filename,old,new):
# import os
# with open(filename,mode='rt',encoding='utf-8') as read_f,\
# open('.db.txt.swap',mode='wt',encoding='utf-8') as wrife_f:
# for line in read_f:
# wrife_f.write(line.replace(old,new))
# os.remove(filename)
# os.rename('.db.txt.swap',filename)
#
# modify_file('db.txt','sb','kevin')

# 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
# def check_list(msg):
# res={
# 'num':0,
# 'string':0,
# 'space':0,
# 'others':0
# }
# for line in msg:
# if line.isdigit():
# res['num'] += 1
# elif line.isalpha():
# res['string'] += 1
# elif line.isspace():
# res['space'] += 1
# else:
# res['others'] += 1
# return res
#
# res=check_list('hello12 342: 1213')
# print(res)

# 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
# def check_list(msg):
# if len(msg)>5:
# print('是')
# else:
# print('否')
# msg=check_list((1,2,[1,2,4,5,5,6]))

# 4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# def check_list(msg):
# if len(msg)>2:
# msg= msg[0:2]
# return(msg)
# print(check_list([1,2,3,4,5]))

# 5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
# def check_list(msg):
# return msg[::2]
# print(check_list([1,2,3,4,5,6,7]))

# 6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# dic = {"k1": "v1v1", "k2": [11,22,33,44]}
# PS:字典中的value只能是字符串或列表
# def check_list(dic):
# for k,v in dic.items():
# if len(v)>2:
# dic[k]=v[0:2]
# return dic
# print(check_list({'k1':'abcdef','k2':[1,2,3,4],'k3':('a','b','c')}))

猜你喜欢

转载自www.cnblogs.com/du-jun/p/9703297.html
今日推荐