1. 程式人生 > >python 替換字串中指定位置字元——一個簡單有效的方法

python 替換字串中指定位置字元——一個簡單有效的方法

方法:序列化字串,存放到列表中,操作改變列表中的內容,最後連線列表內容。

#替換字串string中指定位置p的字元為c
    def sub(string,p,c):
        new = []
        for s in string:
            new.append(s)
        new[p] = c
        return ''.join(new)

該方法可輕鬆實現多個位置的替換:
 #替換字串中多個指定位置為指定字元
    #p:位置列表,c:對應替換的字元列表
    def multi_sub(self,string,p,c):
        new = []
        for s in string:
            new.append(s)
        for index,point in enumerate(p):
            new[point] = c[index]
        return ''.join(new)