So i have a problem where i need to replace a character from a string in an array of strings by providing an x and a y coordinate. In this case, the output should be, that the second "0b000000" has a "1" instead of a "b". However, it either replaces all "b"s in that array, or doesn't replace anything. Here's my code, any help is appreciated:
def setpixel(x, y):
byte_array = [
"0b000000",
"0b000000",
"0b000000",
"0b000000",
"0b000000",
"0b000000",
"0b000000",
"0b000000"
]
line = byte_array[y - 1]
element = line[x - 1]
line.replace(element, "1")
print(byte_array)
setpixel(2, 2)
1 Answer 1
Do
byte_array[y - 1] = line.replace(element, "1")
to actually use the return value of str.replace and make the list reflect that change. But if the element at that pixel happens to occur more than once in that string, this will not work reliably. The safest:
byte_array[y - 1] = line[:x-1] + "1" + line[x:]
And btw, if you are serious about coding, you should get used to 0-indexing! Everything will make so much sense ;-)
line.replaceto do?line.replacereturns a new string. It does not change a string in-place because string characters cannot be altered (strings are therefore immutable; they cannot be mutated)