Replacing instances of a character in a string


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):

It gives the error

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.


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.

12/14/2016 6:33:38 AM

Accepted Answer

Strings in python are immutable, so you cannot treat them as a list and assign to indices.

Use .replace() instead:

line = line.replace(';', ':')

If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:

line = line[:10].replace(';', ':') + line[10:]

That'll replace all semi-colons in the first 10 characters of the string.

10/4/2012 9:01:49 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow