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'))