查找并替换字符串中的字符位置

2024-10-01 02:33:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图替换字符串中的char位置,但到目前为止没有成功。例如,对于

string = 'LOLOLOLO$$'
replace(string,1) 

我想要的结果是

^{pr2}$

我的现有代码:

def replace(string, position):
    p = int(position)
    s = []    
    for i,c in enumerate(string):
        s.append(c)
        if c == '$':
            s.insert(p,c)

    return ''.join(s)

Tags: 字符串代码inforstringifdefposition
2条回答

如果你想把旧的问题移到右边,请插入$:

def replace(src, newpos, what="$$"):
    src=src.replace(what, "")   #removes ALL occurences of what
    return src[:newpos]+what+src[newpos:]

结果是:

^{pr2}$

您仍然在新字符串的末尾附加$符号。试试这个:

...
if c == '$':
    s.insert(p,c)
else:
    s.append(c)

相关问题 更多 >