【问题标题】:Python string.replace() not replacing certain charactersPython string.replace() 不替换某些字符
【发布时间】:2021-03-11 19:45:44
【问题描述】:
def replace_at_index(string, index):
    print (string.replace(string[index], "-", 1))

这是我当前用给定索引替换字符的代码。

  • 索引为 4 的字符串“House”产生“Hous-”
  • 索引为 5 的字符串“Housee”生成“Hous-e”
  • 索引为 6 的字符串“Houseed”产生“Housee-”
  • 索引为 5 的字符串“Houseed”产生“Hous-ed”

不知道为什么会这样。我想要的结果是它替换给定的索引,在“Housee”索引5的情况下将是“House-”

【问题讨论】:

  • 它正在替换您要求它替换的字符的第一次出现。如果有重复的字符,则不一定与您从中获取字符的索引相同。
  • 通常的方式是s = s[0:5] + '-' + s[6:]

标签: python


【解决方案1】:

这是一个 hack,但有效:

def replace_at_index(string, index):
   ls = list(string)
   ls[index] = "-"
   s = "".join(ls)
   print(s)

【讨论】:

  • 这根本不是 hack,这是一个完美的实现。
【解决方案2】:

查看函数doc-string:string.replace(old, new, count) 所以它会尽可能多地替换count

您不能更改字符串。每个字符串都是新创建的,它是不可变的。你想要的是:

def replace_at_index(string, index):
    string = string[:index] + "-" + string[index+1:]
    return string

【讨论】:

    【解决方案3】:

    str.replace 不是替换索引,而是第一次出现的值。由于"Housee"[5] == 'e',它将替换第一个'e'

    def replace_at_index(string, index):
        newstr = string[:index] + '-' + string[index+1:]
        return newstr
    

    【讨论】:

      【解决方案4】:

      replace 方法替换字符串中给定的子字符串。

      代码的作用是替换字符串中第一次出现的字符。

      你应该做的是:

      def replace_at_index(string, index):
          new_string = string[:index]
          new_string += "-"
          new_string += string[index+1:]
          return new_string
      

      以蟒蛇的方式;)

      【讨论】:

      • 字符串是不可变的。
      • 是的。长时间的 C 语言编程导致了这一点
      • 在字符串上使用+=实际上是not super Pythonic,但无论哪种方式,一次加入都更简单:new_string = string[:index] + '-' + string[index+1:]
      • pythonic 我的意思是使用字符串切片。不过感谢您的观察:)
      【解决方案5】:

      它正在替换您要求它替换的字符的第一次出现。如果有重复的字符,则不一定与您从中获取字符的索引相同。

      -- commentBarmar

      您可以做的是在索引处对字符串进行切片,然后将其加入替换。

      def replace_at_index(string, index):
          parts = string[:index], string[index+1:]
          return "-".join(parts)
      
      
      for s, i in ("House", 4), ("Housee", 5), ("Houseed", 6), ("Housee", 5):
          print(replace_at_index(s, i))
      

      输出:

      Hous-
      House-
      Housee-
      House-
      

      尽管您可能需要添加检查以确保 index 在范围内。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-20
        • 2015-08-05
        • 2012-06-23
        • 2018-04-04
        • 1970-01-01
        • 2013-06-02
        • 1970-01-01
        • 2018-08-23
        相关资源
        最近更新 更多