-
编写一个函数,交换指定字典的key和value。
def exchange_keys_and_values(dict1): """ 输出交换键与值之后的字典 """ x = [] y = [] z = [] for i in dict1: x.append(dict1[i]) y.append(i) for a in range(len(x)): z.append([x[a], y[a]]) dict2 = dict(z) print(dict2)
-
编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
def all_alp_in_str(str1): """ 输出提取指定字符串中所有的字母,然后拼接在一起产生的一个新的字符串 """ a = '' for x in str1: if 'a' <= x <= 'z' or 'A' <= x <= 'Z': a += x print(a)
-
写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
def capitalize1(str1): """ 将指定字符串的首字母变成大写字母 """ a = '' count = 0 for x in str1: if 'a' <= x <= 'z' and count == 0: a += chr(ord(x) + ord('A') - ord('a')) else: a += x count += 1 print(a)
-
写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束
def endwith1(str1, str2): """ 判断一个字符串是否已指定的字符串结束 """ if len(str1)<len(str2): print(False) else: a=len(str2) b=str1[-a::] if b == str2: print(True) else: print(False)
-
写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
def isdigit1(str1): """ 判断一个字符串是否是纯数字字符串 """ isdigit=True for x in str1: if not '0'<=x<='9': isdigit=False print(isdigit)
-
写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母
def upper1(a): """ 将一个字符串中所有的小写字母变成大写字母 """ b='' for x in a: if 'a' <= x <= 'z': b += chr(ord(x) + ord('A') - ord('a')) else: b += x print(b)
-
写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
def rjust1(str1, len1, str2): """ 创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充 """ a=len1-len(str1) str3=str2*a+str1 print(str3)
-
写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1
def index1(list1, el1): """ 统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1 """ l=[x for x in range(len(list1)) if list1[x]==el1] if l: print(l) else: print(-1)
-
写一个自己的len函数,统计指定序列中元素的个数
def len1(list1): """ 统计指定序列中元素的个数 """ a=0 for _ in list1: a+= 1 print(a)
-
写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
def max1(list1): """ 获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值 """ a = [] if type(list1) == dict: for x in list1: a.append(list1[x]) else: a = list1 max_elm = a[0] for x in range(len(a)): b=a[x] if max_elm < b: max_elm = b print(max_elm)
-
写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在
def in1(list1,elm1): """ 判断指定序列中,指定的元素是否存在 """ is_in = False for x in range(len(list1)): if elm1 == list1[x]: is_in = True print(is_in)
-
写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串
def replace1(str1, str2, str3): """ 将指定字符串中指定的旧字符串转换成指定的新字符串 """ a = len(str2) new_str = '' if str2 in str1: x = 0 while True: if x == len(str1): break if str1[x: x + a] == str2: new_str += str3 x += a - 1 else: new_str += str1[x] x += 1 print(new_str)
day10-函数作业
最新推荐文章于 2023-03-11 10:00:00 发布