函数作业01

版权声明:此博客实属作者原创,转载请注明出处! https://blog.csdn.net/Onion_cy/article/details/82843870
!/usr/bin/env python 
-*- coding:utf-8 -*-
1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
def func1(file_name, old, new):
    import os
    with open(file_name, mode='r', encoding='utf-8')as read_f, \
            open('.aa.swap', 'w', encoding='utf-8')as write_f:
        for line in read_f:
            if old in line:
                line = line.replace(old, new)
            write_f.write(line)
    os.remove(file_name)
    os.renames('.aa.swap', file_name)

func1('db.txt', 'egon', 'alex')
2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
def func2(msg):
    res={'num':0,'alpha':0,'space':0,'other':0}
    for q in msg:
        if q.isdigit():
            res['num'] +=1
        elif q.isalpha():
            res['alpha'] +=1
        elif q.isspace():
            res['space'] +=1
        else:
            res['other'] +=1
    return res
res=func2(';lkah123 61 ')
print(res)

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def lenth(a):
    print(len(a)>5)
lenth('sdfljkg')

4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def check_len(b):
    if len(b)>2:
        b=b[:2]
    return b
print(check_len([1,2,3,4,5,6,]))
5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
def func3(seq):
    seq=seq[::2]
    return seq
print(func3([1,2,3,4,5,6,7,8,9,10,11]))
6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def func4(seq):
    d={}
    for i,e in seq.items():
        if len(e)>2:
            e=e[:2]
            d[i]=e
        return d
print(func4({"k1": "v1v1", "k2": [11,22,33,44]}))
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表

猜你喜欢

转载自blog.csdn.net/Onion_cy/article/details/82843870
今日推荐