自己实现部分Python字符串操作函数

1.将字符串大写转化为小写 小写转化为大写
def changeCase(str1):
    new_str = ""
    for ch in str1:
        if ch >="a" and ch <= "z":
            new_str += chr(ord(ch) - 32) #小写变大写
        elif ch >= "A" and ch <= "Z":
            new_str += chr(ord(ch) + 32) #大写变小写
        else:
            new_str += ch
    return new_str
print(changeCase("sdaGDFH"))

2.实现统计字符串的长度

def getLength(str1):
    length = 0
    for ch in str1: #计数
        length += 1
    return length

3.字符串中每个单词的首字母转化为大写字母,其他变小写(title函数)

def upperInitial(str1):
    new_str = ""
    tlist = str1.split() #将字符串分割开
    for ch in tlist:
        if ch[0] >="a" and ch[0] <= "z": #首字母小写边大写
            new_str += chr(ord(ch[0]) - 32)
        else:
            new_str += ch[0]  #其他不变
        for v in ch[1:len(ch)]:  #非首字母大写边小写
            if v >= "A" and v <= "Z":
                new_str += chr(ord(v) + 32)
            else:
                new_str += v
        if ch != tlist[-1]:
            new_str += " "
    return new_str

4.给定一个字符串 返回对字符串进行压缩的结果 例如:“aaabcaaddbbc” ——> “a3b1c1a2d2b2c1“

def strCompress(input):
    count = 1
    i = 0
    output = []
    while i < len(input):
        if i + 1 == len(input): #到达字符串末,单独判断是否和倒数第二个字符相同
            output.append(input[i])
            output.append(str(count))
            break
        if input[i] == input[i + 1]: #判断相邻两个字符是否相同
            count += 1  #相同则计数+1
        else:
            output.append(input[i]) #不同则将字符和计数添加到新字符串的末尾
            output.append(str(count))
            count = 1
        i += 1
    output = "".join(output)
    return output

5.实现去除字符串两端指定的内容(strip函数)

def myStrip(input, substr):
    index_start = 0
    index_end = len(input)
    for ch in input:
        if ch in substr: #从左向右遍历字符串,看每个字符是否在子串中
            index_start += 1 #在子串中则开始索引后移
        else:
            break        #否则结束
    for ch in reversed(input): #从右向左遍历字符串,在子串中则结束索引前移
        if ch in substr:
            index_end -= 1
        else:
            break
    return input[index_start:index_end] #返回中间部分字符串

6.自定义在指定区间获得指定字符串中指定子串出现的个数(count函数) 借助使用find功能 

'''
fstr:指定的字符串
substr:要找的子串
start:开始索引
end:结束索引
'''
def myFind(fstr, substr, start, end):
    count = 0  #计数
    index = 0
    while index != -1: #find返回值为-1,结束循环
        index = fstr.find(substr, start, end)
        if index > 0:
            count += 1
            start = start + len(substr) + (index - start) #find找到子串索引,开始索引后移
        else:
            break
    return count

猜你喜欢

转载自blog.csdn.net/Mithrandir_/article/details/81296816
今日推荐