1. 程式人生 > >函數練習

函數練習

bin let 是否 第一題 lac ucc other upd append

#!/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)

函數練習