函数的参数

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

def func(name, **kwargs):
    import os
    if not os.path.exists(r'{}'.format(name)):
        print('文件路径输入错误')
        return
    with open(r'{}'.format(name), 'rb') as f1, \
            open(r'{}.swap'.format(name), 'wb') as f2:
        for line in f1:
            line = line.decode('utf-8')
            if kwargs['old_content'] in line:
                line = line.replace(kwargs['old_content'], kwargs['new_content'])
                f2.write(line.encode('utf-8'))
            else:
                f2.write(line.encode('utf-8'))
        else:
            print('修改完毕')
    os.remove(r'{}'.format(name))
    os.rename('{}.swap'.format(name), '{}'.format(name))


func('a.txt', old_content='裤衩', new_content='大裤衩')

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

def func(str_ori):
    dic = {
        'number': 0,
        'letter': 0,
        'space': 0,
        'others': 0
    }
    for str in str_ori:
        if ord(str) in range(65,91) or ord(str) in range(97,123):
            dic['letter'] += 1
        elif str.isdigit():
            dic['number'] += 1
        elif ord(str) == 32:
            dic['space'] += 1
        else:
            dic['others'] += 1
    return(dic)

res = input('请输入查询字符串:')
rec = func(res)
print('数字为{},字母为{},空格为{},其他为{}'.format(rec['number'],rec['letter'],rec['space'],rec['others']))

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

def func(letter, *args, **kwargs):
    args = list(args)
    print(args)
    print(kwargs)
    str_0 = '<5'
    list_0 = '<5'
    dict_0 = '<5'
    n = 0
    while n < 3:
        if len(letter) > 5:
            str_0 = '>5'
            letter = '1'
        elif len(args) > 5:
            list_0 = '>5'
            args = []
        elif len(kwargs) > 5:
            dict_0 = '>5'
        n += 1
    print('字符串长度{},列表长度{},字典长度{}'.format(str_0, list_0, dict_0))

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

def func(*args):
    # args = list(args)
    # print(args)
    if len(args) > 2:
        x,y = args[0:2]
        return x,y
    else:
        x,y = args
        return x,y

x,y = func(*[1,2])
print(x,y)

def morethan_two(x,y,*args):
    return x,y

x,y = morethan_two(*[1,2,3,4,5,6])
print(x,y)

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

def func(j):
    print(j,type(j))
    l = []
    for i in range(len(j)):
        if i % 2 == 0:
            continue
        else:
            l.append(j[i])
    return l

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

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

def func(dic):
    for i in dic:
        if len(dic[i]) > 2:
            dic[i] = dic[i][0:2]
    # else:
    #     dic[i] = dic[i]
    return dic


dic = {"k1": "v1v1", "k2": [11, 22, 33, 44]}
print(func(dic))

 

posted @ 2020-12-26 15:42  Avery_W  阅读(65)  评论(0编辑  收藏  举报