Python function job learning ----

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

def file_update(name, old_msg, new_msg):
    import os
    with open(f"{name}", "r", encoding="utf-8") as f, \
            open(f".{name}.swap", "w", encoding="utf-8") as f1:
        for line in f:
            f1.write(line.replace(old_msg, new_msg))
    os.remove(name)
    os.rename(f".{name}.swap", name)


file_update("cvc.txt", "a", "b")

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

def func(str):
    n = 0
    c = 0
    space = 0
    o = 0
    for i in str:
        if i.isdigit():
            n += 1
        elif i.isalpha():
            c += 1
        elif i.isspace():
            space += 1
        else:
            o += 1
    print(n, c, space, o)


func('ads11  %')

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

def fun1(n):
    print('判断传入对象的长度是否大于5')
    if len(n) >= 5:
        return True
    else:
        return False


content = input('请输入:')
print(fun1(content))

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 funtion(x):
    if len(x) > 2:
        return x[0:2]


li = [1, 2, 3, 4, 5, 6, 7]
print(funtion(li))

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 nmber(x):
    a = [x[i] for i in range(len(x)) if not i % 2 == 0]
    return a


list = [0, 1, 2, 3, 4, 5, 6, 7, 8]
b = nmber(list)
print(b)

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.

PS: the dictionary value can only be a string or list

dic = {"a": "b", "c": [1, 2, 3, 4]}

def dic2(dic):
    for i in dic:
        if len(dic[i]) > 2:
            dic[i] = dic[i][0:2]
    return dic

res = dic2(dic)
print(res)

Guess you like

Origin www.cnblogs.com/x945669/p/12521542.html