Replacing instances of a character in a string

2018-12-31 20:46发布

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]==";" and i in rightindexarray):
         line[i]=":"

It gives the error

line[i]=":"
TypeError: 'str' object does not support item assignment

How can I work around this to replace the semicolons by colons? Using replace does not work as that function takes no index- there might be some semicolons I do not want to replace.

Example

In the string I might have any number of semicolons, eg "Hei der! ; Hello there ;!;"

I know which ones I want to replace (I have their index in the string). Using replace does not work as I'm not able to use an index with it.

标签: python string
9条回答
荒废的爱情
2楼-- · 2018-12-31 21:18

If you are replacing by an index value specified in variable 'n', then try the below:

def missing_char(str, n):
 str=str.replace(str[n],":")
 return str
查看更多
情到深处是孤独
3楼-- · 2018-12-31 21:19

You can do the below, to replace any char with a respective char at a given index, if you wish not to use .replace()

word = 'python'
index = 4
char = 'i'

word = word[:index] + char + word[index + 1:]
print word

o/p: pythin
查看更多
梦寄多情
4楼-- · 2018-12-31 21:20

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

查看更多
登录 后发表回答