这个简单的代码只是试图用冒号替换分号(在i指定的位置)不起作用:
for i in range(0,len(line)):
if (line[i]==";" and i in rightindexarray):
line[i]=":"
Run Code Online (Sandbox Code Playgroud)
它给出了错误
line[i]=":"
TypeError: 'str' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
我如何解决这个问题用冒号代替分号?使用replace不起作用,因为该函数不带索引 - 可能有一些我不想替换的分号.
例
在字符串中我可能有任意数量的分号,例如"Hei der !; Hello there;!;"
我知道我想要替换哪些(我在字符串中有他们的索引).使用replace不起作用,因为我无法使用索引.
Mar*_*ers 169
python中的字符串是不可变的,因此您不能将它们视为列表并分配给索引.
.replace()改为使用:
line = line.replace(';', ':')
Run Code Online (Sandbox Code Playgroud)
如果您只需要更换某些分号,则需要更具体.您可以使用切片来隔离要替换的字符串部分:
line = line[:10].replace(';', ':') + line[10:]
Run Code Online (Sandbox Code Playgroud)
这将替换字符串前10个字符中的所有分号.
Din*_*s91 56
如果您不想使用,可以执行以下操作,以使用给定索引处的相应char替换任何char .replace()
word = 'python'
index = 4
char = 'i'
word = word[:index] + char + word[index + 1:]
print word
o/p: pythin
Run Code Online (Sandbox Code Playgroud)
nne*_*neo 24
将字符串转换为列表; 然后你可以单独更改字符.然后你可以把它放回去.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
Run Code Online (Sandbox Code Playgroud)
如果要替换单个分号:
for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]
Run Code Online (Sandbox Code Playgroud)
虽然没有测试过它.
| 归档时间: |
|
| 查看次数: |
268458 次 |
| 最近记录: |