You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何根据x、y坐标替换字符串列表内指定位置的字符

问题原因
  • Python 字符串是不可变类型,str.replace() 不会修改原字符串,仅返回替换后的新字符串,你当前代码没有接收该返回值,操作无效。
  • 即使生成了修改后的新字符串,也没有将其重新赋值回数组的对应位置,原数组不会发生变化。
  • replace()会替换字符串内所有匹配的字符,不符合按坐标位置修改单个字符的需求,容易误替换其他同字符内容。
修正代码
def setpixel(x, y):
    byte_array = [
            "0b000000",
            "0b000000",
            "0b000000",
            "0b000000",
            "0b000000",
            "0b000000",
            "0b000000",
            "0b000000"
    ]
    line_index = y - 1
    char_index = x - 1
    # 用字符串切片拼接实现指定位置字符替换
    modified_line = byte_array[line_index][:char_index] + "1" + byte_array[line_index][char_index+1:]
    # 将修改后的行重新赋值回数组
    byte_array[line_index] = modified_line
    print(byte_array)

setpixel(2, 2)
运行结果

调用setpixel(2,2)后输出如下,符合预期将第二个元素的b替换为1:

['0b000000', '01000000', '0b000000', '0b000000', '0b000000', '0b000000', '0b000000', '0b000000']

内容的提问来源于stack exchange,提问作者Softwaretyp Ausm Osten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:36:05