为了账号安全,请及时绑定邮箱和手机立即绑定

替换字符串中字符的实例

替换字符串中字符的实例

qq_遁去的一_1 2019-07-11 10:09:03
替换字符串中字符的实例这段简单的代码试图用冒号替换分号(在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个赞

python中的字符串是不可变的,因此不能将它们作为一个列表来分配给索引。

使用.replace()相反:

line = line.replace(';', ':')

如果您只需要替换分号,你需要更具体。可以使用切片隔离要替换的字符串的区段:

line = line[:10].replace(';', ':') + line[10:]

它将替换字符串前10个字符中的所有分号。


查看完整回答
反对 回复 2019-07-11
?
慕容森

TA贡献1853条经验 获得超18个赞

如果不想使用,可以在给定索引处用相应的字符替换任何字符,如下所示.replace()

word = 'python'index = 4char = 'i'word = word[:index] + char + word[index + 1:]print word

o/p: pythin


查看完整回答
反对 回复 2019-07-11
?
紫衣仙女

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


查看完整回答
反对 回复 2019-07-11
  • 3 回答
  • 0 关注
  • 453 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信