zoukankan      html  css  js  c++  java
  • 函数的基础练习题

    1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
    def modify_file(filename,old,new):
    import os
    with open(filename,'r',encoding='utf+8')as read_f,
    open('.bak.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(filename)
    os.rename('.bak.swap',filename)
    modify_file('/Users/jieli/PycharmProjects/爬虫/a.txt','alex','SB')


    2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
    def check_str(msg):
    res={
    'num':0,
    'string':0,
    'space':0,
    'other':0,
    }
    for i in msg:
    if i.isdigit():
    res['num']+=1
    elif i.isalpha():
    res['string']+=1
    elif i.isspace():
    res['space']+=1
    else:
    res['other']+=1
    return res
    res=check_str('hello name:asB passowrd:alex3714')
    print(res)
    # 及如果:
    # {'num': 4, 'string': 24, 'space': 2, 'other': 2}



    3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
    def user(*seq):
    if len(seq)>5:
    print('正确')
    else:
    print('错误')
    user(2,3,4,5,6,7,8)
    # 结果:
    # [1, 3, 8, 7]

    4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
    def user(seq):
    if len(seq)>2:
    seq= seq[0:2]
    return seq
    print(user([1,2,3,4,5]))
    5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

    def func2(seq):
    return seq[::2]
    print(func2([1, 4, 3, 4, 8, 11, 7]))
    # 结果:[1, 3, 5, 7]

    6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
    # dic = {"k1": "v1v1", "k2": [11,22,33,44]}
    # PS:字典中的value只能是字符串或列表
    def foo(dic):
    d={}
    for k,v in dic.items():
    if len(v)>2:
    d[k]=v[0:2]
    return d
    print(foo({"k1": "v1v1v3v4", "k2": [11,22,33,44],"k3":('a','b','c')}))
    # 结果:
    # {'k1': 'v1', 'k2': [11, 22], 'k3': ('a', 'b')}


  • 相关阅读:
    【整理】Web页面防止重复提交
    C#域验证的代码
    【整理】delegate+RemotingServices 委托+远程调用的一个实例
    【转载】框架里跨域Session丢失问题
    转贴:谈谈多线程的思维方式
    list,vector,deque有什么区别
    转贴:.NET多线程编程(3):线程同步
    转贴:.NET多线程编程(1):多任务和多线程
    转贴:.NET多线程编程(2):System.Threading.Thread类
    转贴:.NET多线程编程(4):线程池和异步编程
  • 原文地址:https://www.cnblogs.com/xuecaichang/p/9392227.html
Copyright © 2011-2022 走看看