-
编写一个函数,交换指定字典的key和value。
def fan0(dict1): dict2={} for key,value in dict1.items(): dict2.setdefault(value,key) return dict2 dict1={'a':1, 'b':2, 'c':3} print(fan0(dict1))
-
编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
def new0(str1): str2='' for stri in str1: if 'a'<=stri<='z' or 'A'<=stri<='Z': str2+=stri return str2 str1='12a&bc12d-+' print(new0(str1))
-
写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
def capitalize1(str1): str2='' for index, stri in enumerate(str1): if 'a'<=stri<='z': stri=chr(ord(stri)-32) break str2=str1[0:index]+stri+str1[index+1:] return str2 str1='abc' print(capitalize1(str1))
-
写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束
def endswith(str1,str2): if str1[-len(str2):]==str2: return True else: return False str1='abc231ab' str2='ab' print(endswith(str1,str2))
-
写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
def isdigit1(str1): for value in str1: if value not in '0123456789': return False else: return True str1='1234921' print(isdigit1(str1))
-
写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母
def upper(str2): m=ord('a')-ord('A') str3='' for xxx in str2: if 'a'<=xxx<='z': xxx=chr(ord(xxx)-m) str3+=xxx return str3 str2='a2h2klm12+' print(upper(str2))
-
写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
def rjust1(str1,str2,a): str3=str2*(6-len(str1))+str1 return str3 a=6 str1='abc' str2='0' print(rjust1(str1,str2,a))
-
写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1
def index1(list1,why): dict0={} for index,value in enumerate(list1): dict0.setdefault(value,index) if why in dict0: return dict0[why] else: return -1 list1=[1, 2, 45, 'abc', 1, '你好', 1, 0] why=45 print(index1(list1,why))
-
写一个自己的len函数,统计指定序列中元素的个数
def len1(str1): a=0 for ss in str1: a+=1 return a str1=(1, 34, 'a', 45, 'bbb') print(len1(str1))
-
写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
例如: 序列:[-7, -12, -1, -9] 结果: -1 序列:'abcdpzasdz' 结果: 'z' 序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98} 结果: 98
-
写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在
def in1(list0,list1): for num in list0: if list1==num: return True else: return False list0=(12, 90, 'abc') list1=12 print(in1(list0,list1))
-
写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串
def replace1(str1,str2,str3): n=0 str4='' while n<len(str1): if str1[n:n+len(str2)]==str2: str4+=str3 n+=len(str2) else: str4+=str1[n] n+=1 return str4 str1='how are you? and you?' str2='you' str3='me' print(replace1(str1,str2,str3))
13.定义一个自己的update函数,将一个字典中所有的键值对添加到另外一个字典中
def update1(dict1,dict2):
for key in dict2: # type: dict
dict1.setdefault(key,dict2[key])
return dict1
dict1={55:1,33:3,77:444}
dict2={'ffa':'ee','sss':'ww','ccc':'gg'}
print(update1(dict1,dict2))