【问题标题】:How to replace chars in string from array of indexes?如何从索引数组中替换字符串中的字符?
【发布时间】:2021-08-25 00:37:06
【问题描述】:

假设我有一个空数组:

ws = []

还有字符串:

text = "cmon lets go"

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

ws = [4, 9]

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

new_string = "cmonzletszgo"

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

new_string = "cmon lets go"

【问题讨论】:

  • 这两个问题还是一个问题?我看不出您的索引列表与字符串中带有 z 的另一个索引列表有何关系。前者似乎只是将replace() 方法用于str 类型。 new_string = new_string.replace('z', ' ')
  • Stackoverflow 不是免费的编码服务。您应该发送honest attempt at the solution,然后然后在必要时询问有关它的具体问题。

标签: python string char


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我只考虑第一部分,它是一个单行。

    ws = [i for i, ch in enumerate(text) if ch.isspace()]
    

    我错过了第二部分的一个关键点,其意图是使用 ws 进行替换。再次,单行:

    new_string = ''.join([' ' if i in ws else ch for i, ch in enumeration(new_string)])
    

    【讨论】:

      猜你喜欢
      • 2014-11-16
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 2010-09-28
      • 2011-10-20
      相关资源
      最近更新 更多