替换字符串中字符的实例 [英] Replacing instances of a character in a string

查看:49
本文介绍了替换字符串中字符的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的代码只是试图用冒号替换分号(在我指定的位置)不起作用:

This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:

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 不起作用,因为该函数没有索引 - 可能有些分号我不想替换.

How can I work around this to replace the semicolons by colons? Using replace does not work as that function takes no index- there might be some semicolons I do not want to replace.

示例

在字符串中我可能有任意数量的分号,例如Hei der! ; Hello there ;!;"

In the string I might have any number of semicolons, eg "Hei der! ; Hello there ;!;"

我知道我想替换哪些(我在字符串中有它们的索引).使用替换不起作用,因为我无法使用索引.

I know which ones I want to replace (I have their index in the string). Using replace does not work as I'm not able to use an index with it.

推荐答案

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

Strings in python are immutable, so you cannot treat them as a list and assign to indices.

改用.replace():

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

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

If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:

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

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

That'll replace all semi-colons in the first 10 characters of the string.

这篇关于替换字符串中字符的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆