函数参数的使用 练习
时间:2020-03-18 14:44:26
收藏:0
阅读:43
# 1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
‘‘‘
import os
def file(file,old,new):
with open(file,mode=‘rt‘,encoding=‘utf-8‘) as f1,open(‘files.txt‘,mode=‘wt‘,encoding=‘utf-8‘) as f2:
for line in f1:
f2.write(line.replace(old,new))
os.remove(file)
os.rename(‘files.txt‘,file)
file(‘db.txt‘,‘tank‘,‘alice‘)
‘‘‘
# 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
‘‘‘
l=‘tank:123: 10007‘
def res(strs):
count1=0
count2=0
count3=0
count4=0
for i in strs:
if i.isdigit():
count1 += 1
elif i.isalpha():
count2 += 1
elif i.isspace():
count3 += 1
else:
count4 += 1
print(count1,count2,count3,count4)
res(l)
‘‘‘
# 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
‘‘‘
l=‘tank:123: 10007‘
l1=[‘tank‘,123,10007]
l2=(‘tank‘,123,10007)
def res(in_put):
if len(in_put) >= 5:
print(True)
else:
print(False)
res(l)
res(l1)
res(l2)
‘‘‘
# 4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
‘‘‘
l=[‘tank‘,123,10007]
def res(lists):
if len(lists) >= 2:
lists=lists[0:2]
print(lists)
res(l)
‘‘‘
# 5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
‘‘‘
l2=(‘tank‘,123,10007)
l=[]
def res(cmd):
cmd=list(cmd)
for i in range(0,len(cmd)):
if i % 2 == 1:
l.append(cmd.pop(i))
print(l)
res(l2)
‘‘‘
# 6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# dic = {"k1": "v1v1", "k2": [11,22,33,44]}
# PS:字典中的value只能是字符串或列表
‘‘‘
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
def res(dicts):
for i in dicts:
l=dicts[i]
if len(l) >= 2:
l=l[0:2]
print(l)
res(dic)
‘‘‘
原文:https://www.cnblogs.com/0B0S/p/12517227.html
评论(0)