defJudgelen(x):returnlen(x)>5
l = Judgelen([1,2,3,4,5,6])if l ==True:print("Yes")else:print("No")print(l)
写函数,检查传入列表的长度,如果大于2, 那么仅保留两个长度的内容,并把新内容返回给调用者
deffunc(l):return l[:2]print(func([1,2,3,4,6]))
写函数,计算传入字符串中【数字】、【字母】、【空格】、以及【其他】的个数,并返回结果
deffunc(s):# num = 0 # 计算数字的个数# alpha = 0 # 计算字母的个数# space = 0 # 空格# other = 0 # 其他
dic ={'num':0,'alpha':0,'space':0,'other':0}for i in s:if i.isdigit():
dic['num']+=1elif i.isalpha():
dic['alpha']+=1elif i.isspace():
dic['space']+=1else:
dic['other']+=1return dic
print(func("0+4-dkajkf 23"))
写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否是空内容,并返回结果
deffunc(x):iftype(x)isstrand x:for i in x:if i ==' ':returnTrueeliftype(x)islistortype(x)istupleand x:for i in x:ifnot i:returnTrueelifnot x:returnTrueprint(func([1,'']))
dic ={'k1':'v1','k2':[1,2,3,4]}# ps:本题字典中的value只能是字符串或列表deffunc(dic):for k in dic:iflen(dic[k])>2:
dic[k]= dic[k][:2]return dic
dic ={'k1':'v1','k2':[1,2,3,4]}print(func(dic))
写函数,接收两个数字参数,返回比较大的那个数字
defcompare_ab(a,b):return a if a>b else b
c = compare_ab(10,12)print(c)
写函数,用户传入修改的文件名,与要修改的内容执行函数,完成整个文件的批量修改操作(进阶)
deffunc(filename, old, new):withopen(filename, encoding='utf8')as f,open('%s.bak'% filename,'w', encoding='utf8')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)
func('修改文件名','12','13')
写函数,接收n个数字,将这些参数数字求和def sum_func(*args): total = 0 for i in args: total += i return totalret = sum_func(15, 2, 8, 35, 45)print(ret)写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返...