替换字符串中字符的实例这段简单的代码试图用冒号替换分号(在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我怎么才能用冒号代替分号呢?使用REPLE不起作用,因为该函数不需要索引-可能有一些分号我不想替换。例在字符串中,我可能有任意数量的分号,如“嗨!;你好;!”我知道我想替换哪些(我在字符串中有它们的索引)。使用替换不起作用,因为我无法使用索引。
3 回答

墨色风雨
TA贡献1853条经验 获得超6个赞
.replace()
line = line.replace(';', ':')
line = line[:10].replace(';', ':') + line[10:]

慕容森
TA贡献1853条经验 获得超18个赞
.replace()
word = 'python'index = 4char = 'i'word = word[:index] + char + word[index + 1:]print word o/p: pythin

紫衣仙女
TA贡献1839条经验 获得超15个赞
.join
:
s = 'a;b;c;d'slist = list(s)for i, c in enumerate(slist): if slist[i] == ';' and 0 <= i <= 3: # only replaces semicolons in the first part of the text slist[i] = ':'s = ''.join(slist)print s # prints a:b:c;d
添加回答
举报
0/150
提交
取消