【问题标题】:Python: String replace indexPython:字符串替换索引
【发布时间】:2016-12-15 19:42:06
【问题描述】:

我的意思是,我想用另一个字符串替换 str[9:11]。 如果我做str.replace(str[9:11], "###") 它不起作用,因为序列 [9:11] 可以不止一次。 如果 str 是 "cdabcjkewabcef" 我会得到 "cd###jkew###ef" 但我只想替换第二个。

【问题讨论】:

  • 使用'string.replace'将给定文本的个出现转换为您输入的文本。您不想这样做,您只想根据其位置(索引)替换文本,而不是根据其内容。

标签: python string python-3.x


【解决方案1】:

你可以的

s="cdabcjkewabcef"
snew="".join((s[:9],"###",s[12:]))

这应该比像snew=s[:9]+"###"+s[12:] 这样在大字符串上加入更快

【讨论】:

    【解决方案2】:

    你可以这样做:

    yourString = "Hello"
    yourIndexToReplace = 1 #e letter
    newLetter = 'x'
    yourStringNew="".join((yourString[:yourIndexToReplace],newLetter,yourString[yourIndexToReplace+1:]))
    

    【讨论】:

      【解决方案3】:

      您可以将join() 与子字符串一起使用。

      s = 'cdabcjkewabcef'
      sequence = '###'
      indicies = (9,11)
      print sequence.join([s[:indicies[0]-1], s[indicies[1]:]])
      >>> 'cdabcjke###cef'
      

      【讨论】:

        【解决方案4】:

        给定 txt 和 s - 你要替换的字符串:

        txt.replace(s, "***", 1).replace(s, "###").replace("***", s)
        

        另一种方式:

        txt[::-1].replace(s[::-1], "###", 1)[::-1]
        

        【讨论】:

          【解决方案5】:
          str = "cdabcjkewabcef"
          print((str[::-1].replace('cba','###',1))[::-1])
          

          【讨论】:

          • 如果您解释了您提供的代码如何回答问题,这将是一个更好的答案。
          【解决方案6】:

          这是一个示例代码:

          word = "astalavista"
          index = 0
          newword = ""
          addon = "xyz"
          while index < 8:
              newword = newword + word[index]
              index += 1
              ind = index
          
          i = 0
          while i < len(addon):
              newword = newword + addon[i]
              i += 1
          
          while ind < len(word):
              newword = newword + word[ind]
              ind += 1
          
          print newword
          

          【讨论】:

            猜你喜欢
            • 2012-08-31
            • 2022-01-03
            • 2010-11-14
            • 2021-10-31
            • 2020-07-26
            • 2021-05-31
            • 2020-01-28
            • 2018-10-28
            • 2018-01-09
            相关资源
            最近更新 更多