-2
row = {"1":"aaaaaaaaaaaaaaaaaaaaaaaaaaa"}

for z in range(1,8,3):
    row["1"][z] = "O"

I want to change the 1,4, and 7th element of the string to "O"

Selcuk
  • 57,004
  • 12
  • 102
  • 110

2 Answers2

0

Python strings are immutable. One way to accomplish what you want is to split the string into a list of characters and mutate that:

char_list = list(row["1"])
for z in range(1, 8, 3):
    char_list[z] = "O"
row["1"] = "".join(char_list)

The new value of row will be:

{'1': 'aOaaOaaOaaaaaaaaaaaaaaaaaaa'}
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Perhaps: `"".join("O" if i in range(1, 8, 3) else ch for i, ch in enumerate(row["1"]))` – Chris Apr 04 '23 at 00:08
0

String are immutable in python, so you can't change it once created. To replace a value at an index, there are several ways of doing it. One easy way is to create a new string, join values before and after the index

row = {"1":"aaaaaaaaaaaaaaaaaaaaaaaaaaa"}
new_value = "o"

for z in range(1,8,3):
    row["1"] = row["1"][:z] + new_value + row["1"][z+1:]

print(row["1"])
#aoaaoaaoaaaaaaaaaaaaaaaaaaa
Ibukun Muyide
  • 1,294
  • 1
  • 15
  • 23
  • Note that this method is dangerous as it will change the length of the string if the `range` exceeds the string length (i.e. `range(1, 58, 3)`). It also creates lots of temporary strings and immediately garbage collects them. – Selcuk Apr 04 '23 at 01:00