ⅩⅣ: Job

1, write function ,, incoming user to modify the file name, and you want to modify the content, perform functions, complete approved a modification operations

import os
def user(name,content,end_content):
    with open(name,'r',encoding='utf-8') as f,\
            open('.name.txt.swp','w',encoding='utf-8') as c1:
        for i in f:
                if content in i:
                    i = i.replace(content,end_content)
                c1.write(i)

    os.remove(name)
    os.rename('.name.txt.swp',name)
user('a.txt','123123','alex')

2, the write function, calculate the incoming string [Digital], [letter],] and the [number of] spaces other [

def str_num(str_count):
    num = 0
    str_1 = 0
    sp = 0
    cou = 0
    for i in str_count:
        if i.isdigit():
            num +=1
        elif i.isspace():
            sp += 1
        elif i.isalpha():
            str_1 += 1
        else:
            cou += 1
    print('数字:%s个\n字母:%s个\n空格:%s个\n其他:%s个' %(num,str_1,sp,cou))

str_num('fu385y3u9rafhwovyb 02tp    8y0 1 bro`4u0989*t&t&*y(*1')

3, write function, the user determines the incoming object (strings, lists, tuples) whether the length is greater than 5.

def user_len(obj_len):
    if len(obj_len) > 5:
        return True
    return False

s = (4253,'egrgerg',25,5252,52532,2142)
ret = user_len(s)
print(ret)

4, write function, check the length of the list passed, if more than 2, then only preserve the contents of the first two lengths, and returns the new content to the caller.

def user_len(obj_len):
    if len(obj_len) > 2:
        return obj_len[:2]
    else:
        return False

ret = user_len([11,1])
print(ret)

5, write function, check all get the odd bit index corresponding elements of the incoming list or tuple object, and returns it to the caller as a new list.

def user(args):
    s = []
    for i in range(len(args)):
        if i % 2 == 1:
            s.append(args[i])
    print(s)

s = ['zz','xx','cc','vv','bb','nn','77','88','99']
user(s)

6, write function, each value of the length of the checking dictionary, if greater than 2, then only preserve the contents of the first two lengths, and returns the new content to the caller.

# dic = {"k1": "v1v1", "k2": [11,22,33,44]}
# PS:字典中的value只能是字符串或列表
def valus_obj(args):
    for i in args:
        if len(args[i]) > 2:
            args[i] = args[i][:2]
    return args

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

Election homework: the same yesterday

Guess you like

Origin www.cnblogs.com/qujiu/p/12519405.html