• 3.18作业


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

    def file_renewal(name,old_msg,new_msg):
        import os
        with open(f"{name}","r",encoding="utf-8") as f ,
            open(f".{name}.swap","w",encoding="utf-8") as f1:
            for line in f :
                f1.write(line.replace(old_msg,new_msg))
        os.remove(name)
        os.rename(f".{name}.swap",name)
    file_renewal("aaa.txt","a","b")
    

      

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

    def count(*args):
        dic = {'num': 0,'letter': 0,'space': 0,'others': 0}
        for i in args:
            if i.isdigit():
                dic['num'] += 1
            elif i.isalpha():
                dic['letter'] += 1
            elif i.isspace():
                dic['space'] += 1
            else:
                dic['others'] += 1
        return dic
    imp = input('input something:')
    res = count(*imp)
    print(res)
    

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

    def len1(x):
        print(len(x)>5)
    
    
    len1([3333,11])
    

      

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

    def list_len(a):
        if len(a)>2:
            return a[0:2]
    res = list_len([5,5,4,4,4,1,1,])
    print(res)
    

      

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

    def odd_number(indexes):
        if not (type(indexes) == type([1,2]) or type(indexes) == type((1,))):
            print('input must be list or tuple')
        else:
            new_indexes = indexes[0::2]
            return new_indexes
    indexes = (2,3,66,1,2,55,2,'aaa')
    res = odd_number(indexes)
    print(res)
    

      

    写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

    dic = {"k1": "v1v1", "k2": [11,22,33,44]}
    def dic_value(a):
        if not type(dic) == type({}):
            print('重新输入')
        for i in a:
            if len(a[i]) > 2:
                a[i] = a[i][0:2]
        return a
    res = dic_value(dic)
    print(res)
    

      

  • 相关阅读:
    JAVA_基础集合List接口与Set接口(二)
    JAVA_基础集合Collection接口与Iterator迭代器(一)
    JAVA_基础注解的概念
    JAVA_基础多线程的生命周期、线程安全、线程锁、线程通信与创建线程(二)
    JAVA_基础多线程(一)
    JAVA_基础异常概述与异常体系的结构
    JAVA_基础内部类
    JAVA_基础面向对象:接口
    Golang 学习资源
    go语言-异常处理机制-panic和recover的使用和原理
  • 原文地址:https://www.cnblogs.com/Tornadoes-Destroy-Parking-Lots/p/12520685.html
Copyright © 2020-2023  润新知