今日作业:
必做题:
1.写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
import os
方式一:同时打开两个文件一起操作
def change_file(file_path,old_msg,new_msg):
with open(file_path,'rt',encoding='utf-8') as f,open('new.txt','wt',encoding='utf-8') as f2:
for line in f:
data=line.replace(old_msg,new_msg)
f2.write(data)
os.remove(file_path) #把源文件删除后,就用rename 重新以源文件的名字命名
os.rename('new.txt',file_path)
os.replace('new.txt',file_path) #如果不删除源文件就用replace替换掉源文件
change_file('old.txt','hello world!','你好,world!')
方式二:一次只打开一个文件进行操作
list=[]
def change_file(path,old_msg,new_msg):
with open(path,'rt',encoding='utf-8') as f:
for line in f:
data=line.replace(old_msg,new_msg)
list.append(data)
with open(path,'wt',encoding='utf-8') as f:
for line in list:
f.write(line)
change_file('old.txt','你好,world','hello world!')
2.写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
def count_str(str):
dict = {'num': 0,'alpha': 0,'space': 0,'others': 0}
for x in str:
if x.isdigit():
dict['num']+=1
elif x.isalpha():
dict['alpha']+=1
elif x.isspace():
dict['space']+=1
else:
dict['others']+=1
print('数字个数为:%s
字母个数为:%s
空格数为:%s
其他字符数为:%s'
%(dict['num'],dict['alpha'],dict['space'],dict['others']))
str=input("输入字符串:")
count_str(str)
3.写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def linecount(line):
if len(line)>5:
print('长度大于5')
else:
print('长度不大于5')
linecount('1323')
linecount([1,2,4,5,6,7])
linecount((1,2,3,5))
4.写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def func(list):
if len(list) >= 2:
return list[:2]
return False
list=[2,6,1,8]
print(func(list))
5.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
def func(some):
new_list=[]
line=len(some)
for i in range(0,line-1):
if i%2==1:
new_list.append(some[i])
return new_list
print(func((1,2,4,5,3,9,7)))
print(func([1,2,4,5,3,9,7]))
6.写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表
def func(dict):
for x in dict:
if len(dict[x])>=2:
dict[x]=dict[x][:2]
return dict
dict={"k1": "v1v1", "k2": [11,22,33,44],"k3": (11,22,33,44)}
print(func(dict))