首页 > 解决方案 > 如何从索引数组中替换字符串中的字符?

问题描述

假设我有一个空数组:

ws = []

和字符串:

text = "cmon lets go"

我将检查空格并在 ws 数组中存储空格索引,因此之后我将拥有:

ws = [4, 9]

然后我会有一些其他的字符串:

new_string = "cmonzletszgo"

假设所有空格都用字母 z 切换(没关系)。现在我想遍历 new_string 并用空格替换数组 ws 中索引中的字符所以我想得到

new_string = "cmon lets go"

标签: pythonstringchar

解决方案


由于您有要替换的索引,因此您可能想尝试迭代ws而不是new_string

for i in ws:
   new_string = new_string[:i] + ' ' + new_string[i + 1:]

这将在new_string中指定的索引处将字符替换为空格ws,而不管当前可能存在什么字符。


推荐阅读