替换字符串中字符的实例

2024-04-20 03:16:22 发布

您现在位置:Python中文网/ 问答频道 /正文

这段简单的代码试图用冒号替换分号(在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

如何解决这个问题,用冒号替换分号?使用replace不起作用,因为该函数不接受索引-可能有一些分号我不想替换。

示例

在字符串中,我可以有任意数量的分号,例如“Hei der!;你好;!;“

我知道我要替换哪些(字符串中有它们的索引)。使用replace不起作用,因为我不能对它使用索引。


Tags: and字符串代码inforlenif错误
3条回答

将字符串转换为列表;然后可以单独更改字符。然后你可以把它和.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

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

请改用^{}

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

如果只需要替换某些分号,则需要更具体。可以使用切片来隔离要替换的字符串部分:

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

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

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

word = 'python'
index = 4
char = 'i'

word = word[:index] + char + word[index + 1:]
print word

o/p: pythin

相关问题 更多 >