1、封裝類似lower()的函數 2、封裝類似upper()的函數 3、封裝類似find()的函數 4、封裝類似rfind()的函數 5、封裝功能類似isdigit()的函數 6、封裝功能類似partition()的函數 ...
1、封裝類似lower()的函數
def myLower(src): src1 = '' for i in src: if 'A' <= i <= 'Z': src1 += chr(ord(i) + 32) else: src1 += i return src1 #print(myLower('AcdEjlG'))
2、封裝類似upper()的函數
def myUpper(src): src1 = '' for i in src: if 'a' <= i <= 'z': src1 += chr(ord(i) - 32) else: src1 += i return src1 #print(myUpper('aCdEf'))
3、封裝類似find()的函數
第一種思路: def myFind1(src,sub): for i in range(len(src)-len(sub)+1): new_src = src[i:i+len(sub)] #print(new_src) if new_src == sub: return i else: return -1 print(myFind1('abcde123abe','123a')) 第二種思路: def myFind(src,sub): if len(sub) > len(src): return -1 for i in range(len(src)): if src[i] == sub[0]: index = i for j in range(len(sub)): if src[index] != sub[j]: break index += 1 else: return i else: return -1
4、封裝類似rfind()的函數
第一種思路: def myRfind(src,sub): #從右往左進行遍歷 for i in range(len(src)-1,-1,-1): #先找第一個字元,如果一致,在進行對應切片比較 if sub[0] == src[i]: #如果切片出來的結果與子串一致,返回所在的索引值 if sub == src[i:i+len(sub)]: return i #如果沒找到,返回-1 else: return -1 # index = myRfind('abc123','c1') # print(index) 第二種思路: def myRfind(src,sub): if len(sub) > len(src): return -1 for i in range(-1,-len(src)-1,-1): if src[i] == sub[0]: index = i for j in range(len(sub)): if src[index] != sub[j]: break index += 1 else: return len(src) + i else: return -1 #print(myRfind('abcdegabeda','ab'))
5、封裝功能類似isdigit()的函數
def myIsdigit(src): for ch in src: if not '0' <= ch <= '9': return False else: return True print(myIsdigit('123')) print(myIsdigit('123a'))
6、封裝功能類似partition()的函數
def myPartition(src,sub): if sub in src: #獲取子串在目標字元串的索引值 index = myRfind(src,sub) #切片操作劃分三個元素: 1.str[0:index] 2.sub 3.[index+len(sub):] return (src[0:index],sub,src[index+len(sub):]) else: return (src,'','') # print(myPartition('abcdef','g')) print(myPartition('abcdef','cd'))