0

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)
4
  • Strings are immutable. What did you expect line.replace to do? Commented Oct 28, 2021 at 18:43
  • Also, each time you call the function, you redefine the array, so there wouldnt be any persistent change Commented Oct 28, 2021 at 18:45
  • line.replace returns 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) Commented Oct 28, 2021 at 18:49
  • Didn't realize it doesn't change the original String. With the answer below it finally works, thanks for your help anyways. Commented Oct 28, 2021 at 18:54

1 Answer 1

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 ;-)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I'll look into it, you really helped me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.