0 votes
1 view
in Python by (47.8k points)

This simple code that simply tries to replace semicolons (at i-specified positions) 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.

1 Answer

0 votes
by (107k points)

For replacing instances of a character in string 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

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Oct 4, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Sep 10, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...