简体   繁体   中英

Replacing characters from a String List in python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM