• 函数参数作业


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

    def change_file(file_path,old,new):
        with open(file_path,'rt',encoding='utf-8')as f:
            data = f.read()
        with open(file_path,'wt',encoding='utf-8')as w:
            w.write(data.replace(old,new))

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

    def count_num(str):
        int_count=str_count=none_count=other_count=0
        for i in str:
            if i.isdigit():
                int_count+=1
            elif i.isalnum():
                str_count+=1
            elif i==' ':
                none_count+=1
            else:
                other_count+=1
        print('数字:{}
    字母:{}
    空格:{}
    其他:{}
    '.format(int_count,str_count,none_count,other_count))
    count_num('a d555 as %&$d')

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

    def count_len(obj):
        res = len(obj)
        print('长度为%s'%(res))
    count_len('asd')

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

    def change_list(list):
        list1=[]
        res = len(list)
        if res > 2:
           for i in range(2):
               list1.append(list[i])
        return list1
    res = change_list([1,2,3,4,5])
    print(res)

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

    def odd_index(obj):
        list=[]
        for i in range(len(obj)):
            if i % 2 != 0:
                list.append(obj[i])
        return list
    res = odd_index([1,2,3,4])
    print(res)

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

    dic = {"k1": "v1v1", "k2": [11,22,33,44]}
    # PS:字典中的value只能是字符串或列表
    def change_dic(dic):
        for i in dic:
            if len(dic[i]) > 2:
                dic[i]=dic[i][0:2]
        return dic
    dic = change_dic(dic)
    print(dic)
  • 相关阅读:
    php 数组去重
    投票 页的做法 重点——学会进度条!!
    封装 类
    HPH-——>mysql 批量删除
    php->msql 多条件查询
    php-> msql 修改
    PHP ->masql 登录 增 删 改
    php 连接数据库
    Python 第十七章 序列化+os+sys+hashlib+collections
    Python 第十六章 自定义模块+time+datetime+random
  • 原文地址:https://www.cnblogs.com/bk134/p/12519303.html
Copyright © 2020-2023  润新知