函数练习
#!/usr/bin/env python # -*- coding:utf-8 -*- # by wk ''' 1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。 4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。 5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。 6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。 dic = {"k1": "v1v1", "k2": [11,22,33,44]} PS:字典中的value只能是字符串或列表 ''' import os # 第一题 def update_file(old, new): with open('test.txt', 'r', encoding='utf8') as read_f, open('test_new.txt', 'w', encoding='utf8') as write_f: for line in read_f: if old in line: line = line.replace(old, new) write_f.write(line) os.remove('test.txt') os.rename('test_new.txt', 'test.txt') print('update success') # 第二题 def count_enter(mystrings): count = 0 mystring_list = [0, 0, 0, 0] for mystring in mystrings: if mystring.isdigit(): mystring_list[0] += 1 elif mystring.isalpha(): mystring_list[1] += 1 elif mystring.isspace(): mystring_list[2] += 1 else: mystring_list[3] += 1 print('num is %s, letter is %s, Space is %s, Other is %s' % ( mystring_list[0], mystring_list[1], mystring_list[2], mystring_list[3])) # 第三题 def check_len(mystrings): if type(mystrings) == str: if len(mystrings) > 5: print('this is str and len > 5') else: print('this is str but len =< 5') elif type(mystrings) == list: if len(mystrings) > 5: print('this is list and len > 5') else: print('this is list but len =< 5') elif type(mystrings) == tuple: if len(mystrings) > 5: print('this is tuple and len > 5') else: print('this is tuple but len =< 5') # 第四题 def check_list_len(mystrings): if len(mystrings)>2: print(mystrings[0:2]) else: print(mystrings) # 第五题 def check_odd(mystrings): i = 0 new_mystrings = [] while True: if i > len(mystrings)-1: break new_mystrings.append(mystrings[i]) i += 2 print(new_mystrings) #第六题 def my_dic(mylendict): new_mydict = {} print(type(mylendict)) for lenv in mylendict: if len(mylendict[lenv]) > 2: new_mydict[lenv] = mylendict[lenv][0:2] else: new_mydict[lenv] = mylendict[lenv] print(new_mydict) if __name__ == '__main__': update_file('a', 'b') count_enter('asdasda123 @#$$') check_len([1, 2, 3, 4, 5]) check_len((1, 2, 3, 4, 5, 6)) check_len('aaaaaaaaaa') check_list_len(['a',1,2,'b','c',6]) check_odd(['a',3,6,'g',5]) dic = {"k1": "v1v1", "k2": [11, 22, 33, 44]} my_dic(dic)