Replacing instances of a character in a string

前端 未结 13 2654
谎友^
谎友^ 2020-11-22 07:19

This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:

for i in range(0,len(line)):
     if (line[i]==\"         


        
13条回答
  •  庸人自扰
    2020-11-22 07:48

    This should cover a slightly more general case, but you should be able to customize it for your purpose

    def selectiveReplace(myStr):
        answer = []
        for index,char in enumerate(myStr):
            if char == ';':
                if index%2 == 1: # replace ';' in even indices with ":"
                    answer.append(":")
                else:
                    answer.append("!") # replace ';' in odd indices with "!"
            else:
                answer.append(char)
        return ''.join(answer)
    

    Hope this helps

提交回复
热议问题