zoukankan      html  css  js  c++  java
  • 作业day12

    2020-06-16

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

    import os
    
    
    def change_file(file_path, old_data, new_data):
        if not os.path.exists(file_path):
            print("输入的文件路径不存在")
            return
        with open(file_path, mode='r', encoding='utf-8') as f:
            res = f.read()
            if old_data not in res:
                print("要修改的内容不存在")
                return
            new_res = res.replace(old_data, new_data)
            with open(file_path, mode='w', encoding='utf-8')as p:
                p.write(new_res)
                print("修改完成")

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

    def count(msg):
        num_count = 0
        letter_count = 0
        space_count = 0
        others_count = 0
        for i in msg:
            if i.isdigit():
                num_count += 1
            elif i.isalpha():
                letter_count += 1
            elif i.isspace():
                space_count += 1
            else:
                others_count += 1
        print({'number': num_count, 'letter': letter_count, 'space': space_count, 'others': others_count})
    
    
    count()

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

    def length(a):
        if len(a) >= 5:
            print("%s的长度大于5" % type(a))
        else:
            print("%s的长度小于5" % type(a))

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

    def change_list(l):
        if len(l) >= 2:
            l = l[0:2]
            return l
    
    
    res = change_list([1, 2, 3])
    print(res)

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

    def list_func(l):
        m = []
        for i in range(1, len(l), 2):
            m.append(l[i])
    
        return m
    
    
    res = list_func([1, 2, 3, 4, 5])
    print(res)
    def list_func(l):
            return l[1::2]
    
    
    res=list_func([1,2,3,4,5])
    print(res)

    6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
    dic = {"k1": "v1v1", "k2": [11,22,33,44]}
    PS:字典中的value只能是字符串或列表

    def func(dic):
        for k, v in dic.items():
            if len(v) > 2:
                dic[k] = v[0:2]
        return dic
    
    
    res = func({"k1": "v1v1", "k2": [11, 22, 33, 44]})
    print(res)
  • 相关阅读:
    visual studio 注释与取消注释
    visual studio错误之 无法将参数 1 从“const char [5]”转换为“char *”
    sdl_ffmpeg_video
    sdl_ffmpeg_audio
    visual studio添加第三方库文件,每次都要配置包含目录和库目录(繁琐),一劳永逸的办法
    visual studio 错误之errorC2362:“gototmpstr”跳过了“XXXX”的初始化操作
    visual studio调用SDL2和ffmpeg
    没用过得库函数
    visual studio编译错误之xx被声明为已否决
    vim把一个文件的若干行追加到另一个文件
  • 原文地址:https://www.cnblogs.com/cui-cheng/p/13150126.html
Copyright © 2011-2022 走看看