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.
To replace a character at a specific index, the function is as follows:
where s is a string, n is index and c is a character.
Turn the string into a list; then you can change the characters individually. Then you can put it back together with
.join
:Strings in python are immutable, so you cannot treat them as a list and assign to indices.
Use
.replace()
instead: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:
That'll replace all semi-colons in the first 10 characters of the string.
If you want to replace a single semicolon:
Havent tested it though.
You cannot simply assign value to a character in the string. Use this method to replace value of a particular character:
Output: In*ia
Also, if you want to replace say * for all the occurrences of the first character except the first character, eg. string = babble output = ba**le
Code:
How about this: