1. 程式人生 > >Python程式設計之路 ---- 練習3

Python程式設計之路 ---- 練習3

1.寫函式,修改指定檔案中的內容,使用者傳入修改的檔名,與要修改的內容,執行函式,完成批了修改操作

def batch_edit(filename,old_contcnt,new_content):
    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_name in line:
                line=line.replace(old_content,new_content)
            write_f.write(line)
    os.remove(filename)
    os.rename('.bak.swap',filename)
batch_edit('D:\test.txt','aaa','bbb')

2.寫函式,計算傳入字串中【數字】、【字母】、【空格] 以及 【其他】的個數 

def count_type(lst):
    import string
    digitl_count=0
    alpha_count=0
    space_count=0
    other_count=0
    for t in lst:
        if t.isspace():
            space_count+=1
        elif t.isalpha():
            alpha_count+=1
        elif t.isdigit():
            digitl_count+=1
        else:
            other_count+=1
    print ('d_count=%s,a_count=%s,s_count=%s,other_count=%s'%(digitl_count,alpha_count,space_count,other_count))


count_type('fdafda 156456615 $%%')

3.寫函式,判斷使用者傳入的物件(字串、列表、元組)長度是否大於5。

def judgment(*args):
    lst = input('>>>:',*args)
    if len(lst) > 5:
        print('object lenth > 5')
    else:
        print('object lenth <5')
judgment()

4.寫函式,檢查傳入列表的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給呼叫者。

def judgment(lst):
    if len(lst)> 2:
         return lst[0:2]
    else:
        print('object lenth <5')

print(judgment([' ','shgs',43243]))

5.寫函式,檢查獲取傳入列表或元組物件的所有奇數位索引對應的元素,並將其作為新列表返回給呼叫者。

def fu(lst):
    i=0
    new_lst=[]
    for lst[i] in lst:
        if i%2 ==0:
            pass
        else:
            new_lst.append(lst[i])
        i+=1
    print(new_lst)


fu(['adafd','a','111','123'])

6.寫函式,檢查字典的每一個value的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給呼叫者。    dic = {"k1": "v1v1", "k2": [11,22,33,44]}    PS:字典中的value只能是字串或列表

def fuc(input):
    dict={}
    for key,item in input.items():
       if len(item) > 2:
           dict[key] = item[:2]
    return dict

print(fuc({'u1':'123456','u2':'234567','u3':'345678'}))