作业0318

1、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作

def change_files(file_path,old,new):
    '''批量修改文件的函数'''
    list1=[]
    with open(file_path,'r',encoding='utf-8') as f:
        for line in f:
            line=line.replace(old,new)
            list1.append(line)
            print(list1)
    with open (file_path,'w',encoding='utf-8') as f1:
        for line in list1:
            f1.write(line)

change_files()

2、写函数,计算传入字符串中【数字】、【字母】、【空格】 以及 【其他】的个数

def str_counts(str1):
    '''计算传入字符串中【数字】、【字母】、【空格】 以及 【其他】的个数'''
    dig_num = 0
    alp_num = 0
    space_num = 0
    other_num = 0
    for x in str1:
        if x.isdigit():
            dig_num += 1
        elif x.isalpha():
            alp_num += 1
        elif x.isspace():
            space_num += 1
        else:
            other_num += 1
    print('字符串中【数字】{}个、【字母】{}个、【空格】{}个、【其他】{}个'.format(dig_num,alp_num,space_num,other_num))
str_counts()

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

def more_than_5():
    inp_sth = input('请输入要检测的对象(字符串、列表、元组):')
    if inp_sth.startswith('[') and inp_sth.endswith(']'):
        inp_sth = inp_sth.strip('[').strip(']').replace(',','')
        res = len(inp_sth)
    elif inp_sth.startswith('(') and inp_sth.endswith(')'):
        inp_sth = inp_sth.strip('(').strip(')').replace(',', '')
        res = len(inp_sth)
    else:
        res = len(inp_sth)
    print(res)

more_than_5()

4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

def more_than_2(x, y, *args):
    return x, y
x, y = more_than_2(*[1, 2, 3, 4, 5, '6'])
print(x,y)

5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

def return_single(old_list):
    if type(old_list)==list or type(old_list)==tuple:
        new_list = []
        for i in old_list:
            if  old_list.index(i)%2 == 1:
                new_list.append(i)
    else:
        print("输入的类型不是列表或元组,请重新输入!")
    return new_list
res = return_single([1,2,3,4,5])
print(res)

dic = {"k1": "v1v1", "k2": [11,22,33,44]}
def more_than_2(a):
    for i in a:
        if len(a[i]) > 2:
            a[i] = a[i][0:2]
    return a
res = more_than_2(dic)
print(res)