替換字符串中字符的實例這段簡單的代碼試圖用冒號替換分號(在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不起作用,因為該函數(shù)不需要索引-可能有一些分號我不想替換。例在字符串中,我可能有任意數(shù)量的分號,如“嗨??;你好;!”我知道我想替換哪些(我在字符串中有它們的索引)。使用替換不起作用,因為我無法使用索引。
3 回答

墨色風(fēng)雨
TA貢獻(xiàn)1853條經(jīng)驗 獲得超6個贊
.replace()
line = line.replace(';', ':')
line = line[:10].replace(';', ':') + line[10:]

慕容森
TA貢獻(xiàn)1853條經(jīng)驗 獲得超18個贊
.replace()
word = 'python'index = 4char = 'i'word = word[:index] + char + word[index + 1:]print word o/p: pythin

紫衣仙女
TA貢獻(xiàn)1839條經(jīng)驗 獲得超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
提交
取消