day14 练习

# 1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
def file_change(path,file,c_file):
    with open(path,mode='rb')as f:
        x=f.read().decode('utf-8').replace(file,c_file)
    with open(path,mode='wb')as f1:
        f1.write(x.encode('utf-8'))
file_change(r'D:\cool\啦啦啦','','超超超')


# 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
def func(res):
    if type(res) != str:
        print('输入的不是字符串')
    else:
        dic = {'数字': 0, '字母': 0, '空格': 0, '其他': 0}
        for x in res:
            if x.isalpha():
                dic['字母'] += 1
            elif x.isspace():
                dic['空格'] += 1
            elif x.isdigit():
                dic['数字'] += 1
            else:
                dic['其他'] += 1
        print(dic)
func('ni hao 11 ')

# 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def func(res):
    while 1:
        if type(res) == str and len(res)>5:
            print('字符串长度大于5')
            break
        elif type(res) == list and len(res)>5:
            print('列表长度大于5')
            break
        elif type(res) == tuple and len(res)>5:
            print('元祖长度大于5')
            break
        else:
            break

func((1,2,3,3,3,3,3))


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

def func(res):
    if type(res)!=list:
        print('不是列表类型')
    else:
        if len(res)>2:
            return res[:2]


print(func([3,2,3,4,5]))


# 5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
def func(res):
    if type(res)!=list and type(res)!=tuple:
        print('不是列表和元祖')
    else:
        return res[::2]
print(func((91,2,3,1,31,3,1230)))






# 6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
# PS:字典中的value只能是字符串或列表
def func(res):
    l = []
    for x in res.values():
        # print(x)
        if type(x)==str or type(x)==list:
            l.append(x[:2])
        else:
            print('value不是字符串或不是列表')
    return l

print(func(dic))

 

posted @ 2020-03-18 23:56  It's_cool  阅读(172)  评论(0)    收藏  举报