kakajiejie

Python函数

#写函数,计算传入的字符串中【数字】,【字母】,【空格】及【其他】的个数,并返回结果
def func(a):
dic = {'数字':0,'字母':0,'空格':0,'其他':0}
for i in a:
if i.isdigit():
dic['数字'] += 1
elif i.isalpha():
dic['字母'] += 1
elif i.isspace():
dic['空格'] += 1
else:
dic['其他'] += 1
return dic
print(func('1231&*('))

#写函数,检查用户传入的对象(字符串,列表,元祖)的每一个元素是否含有空内容,并返回结果:
def func(x):
if type(x) is str and x:
for i in x:
if i == ' ':
return True
elif x and type(x) is list or type(x) is tuple:
for i in x:
if not i:
return True
elif not x:
return True
print(func(('2','','3',4)))

#写函数、检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者dic = {"k1":"v1v2","k2":[11,22,33,44,66]}
def func(dic):
for i in dic:
if len(dic[i]) > 2:
dic[i] = dic[i][:2]
return dic
dic = {"k1":"v1v2","k2":[11,22,33,44,66]}
print(func(dic))

#写函数,用户传入修改的文件名,与修改的内容;
def func(filename,old,new):
with open(filename, encoding='utf-8') as f, open('%s.bak'%filename, 'w', encoding='utf-8') as f2:
for line in f:
if old in line:
line = line.replace(old, new)
# 写文件
f2.write(line)

import os
os.remove(filename) # 删除文件
os.rename('%s.bak'%filename, filename) # 重命名文件

posted on 2021-04-15 17:22  kakajiejie  阅读(70)  评论(0编辑  收藏  举报

导航