当前位置 : 主页 > 编程语言 > python >

Python初学第二段代码

来源:互联网 收集:自由互联 发布时间:2022-06-15
# 1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作 def func1(x, y, z): import os with open(r'{}'.format(x), mode='rt', encoding='utf-8') as f1, \ open(r'.{}.swap'.format(x),
# 1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
def func1(x, y, z):
import os
with open(r'{}'.format(x), mode='rt', encoding='utf-8') as f1, \
open(r'.{}.swap'.format(x), mode='wt', encoding='utf-8') as f2:
while True:
res1 = f1.readline()
if len(res1) == 0:
break
else:
res2 = res1.replace(y, z)
f2.write(res2)

os.remove(r'{}'.format(x))
os.rename(r'.{}.swap'.format(x), r'{}'.format(x))


while True:
Inp_file_path = input('change file [exit]==>> ')
if Inp_file_path == 'exit':
break
elif len(Inp_file_path) == 0:
break
else:
Inp_after = input('change after==>> ')
Inp_before = input('change before==>> ')
func1(Inp_file_path, Inp_after, Inp_before)


# 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
def func2(*args):
x=0
for i1 in args:
if i1 == 'None':
pass
else:
x += len(str(i1))
return x

print(func2(1,2,3,4,'53343434','abewebwew'))


# 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def func3(*args):
res1=len(args)
if res1 > 5:
return '大于5'
else:
return '小于5'

res2=func3(1,2,3,3,*[1,2,3,4],*(1,3,3,4,5,5))
print(res2)


# 4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def func4(*args):
x = len(list(args))
if x > 2:
res=args[0:2]
return list(res)
else:
pass

print(func4(*['哈哈哈','你好',123434,'aawew']))


# 5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
def func5(*args):
res1=len((args[0]))
res2=[]
for i1 in range(res1):
if i1 % 2 == 0:
res2.append(args[0][i1])
else:
pass
return res2

print(func5([1,2,3,6,7,3,7,8,9]))

#加油学,加油学,加油学,学不死就往死里学!!!!
上一篇:如何内网搭建pip源?
下一篇:没有了
网友评论