Say I have a list indices
. I also have a character char
. The third argument is a string string
. I want to return a copy of string
such that string[index] = char
for all index in indices
.
I do have a function that does this, but I believe that it is inefficient. It is
newString = string
for index in indices:
newString = newString[:index] + char + newString[index+1:]
The first line makes a copy of the string. Then it iterates through all indices that need to be changed and makes the index equal to char
.
According to this question, the efficiency of slicing a string is O(n)
, which would then make the efficiency of the above code O(nm)
, where n
is the length of the string, and m
is the length of indices
. I was hoping for a faster solution.
Any improvement would be appreciated.
Edit: An example would be with string = "qwertyuoip", indices = [0, 4, 5, 8], char = "1"
. Then the 0th, 4th, 5th, and 8th character of string would be replaced with char. The output should be newString = "1wer11ui1p"
.