这个简单的代码试图用冒号替换分号(在 i 指定的位置)不起作用:
for i in range(0,len(line)):
if (line[i]==";" and i in rightindexarray):
line[i]=":"
它给出了错误
line[i]=":"
TypeError: 'str' object does not support item assignment
我该如何解决这个问题,用冒号替换分号?使用替换不起作用,因为该函数不需要索引 - 可能有一些分号我不想替换。
例子
在字符串中,我可能有任意数量的分号,例如“Hei der! ; Hello there ;!;”
我知道要替换哪些(我在字符串中有它们的索引)。使用替换不起作用,因为我无法使用索引。
原文由 The Unfun Cat 发布,翻译遵循 CC BY-SA 4.0 许可协议
python 中的字符串是不可变的,因此您不能将它们视为列表并分配给索引。
使用
.replace()
代替:如果您只需要替换 某些 分号,则需要更具体。您可以使用切片来隔离要替换的字符串部分:
这将替换字符串前 10 个字符中的所有分号。