【问题标题】:How to replace specific part of a string (replace() dosen't help...) [closed]如何替换字符串的特定部分(replace()没有帮助......)[关闭]
【发布时间】:2020-04-09 14:13:36
【问题描述】:
a = "hello world, hello there, hello python"

如何只将中间的“hello”改为“hi”? 提前致谢! 编辑: 即使字符串是'hi world,hello there,hello python',我也想更改唯一的中间hello,在这种情况下,目标“hello”是第一次出现,而在第一种情况下是第二次

【问题讨论】:

  • a.replace("hello there", "hi there") 是否可以接受,或者您是否更一般地考虑如何替换字符串中的中间元素?
  • 是的,寻找一种更通用的方式,只替换“hello”
  • 我不知道它是第一次还是第二次出现子字符串(输入可能会有所不同)所以我不知道每行的 n 值来替换第 n 项。

标签: python string replace


【解决方案1】:

我不确定你想要的通用性。如果它符合您的要求,请检查:

def replace_middle(target, replacement, string):
    list_a = string.split()
    target_ids = [i for i, word in enumerate(list_a) if word == target]
    middle_elem = target_ids[len(target_ids)//2]
    list_a[middle_elem] = replacement
    print(' '.join(list_a))

a = "hello world, hello there, hello python"
replace_middle('hello', 'hi', a)

输出:

hello world, hi there, hello python

【讨论】:

  • 所以我检查了你的代码,它的时间更复杂,需要更多的时间来执行。因为不需要循环来解决问题。您还可以通过替换中间词和第 n 个词来编辑它以使其通用。
  • 我同意你所说的一切。但我不想使用re。如果没有re,您确实需要循环。 OP 要求的是中间那个,而不是Nth。
  • 所以可以直接使用a.replace("hello","hi",2).replace("hi","hello",1)。我也检查了这个,时间是 0.295。否则 index = a.find("hello",2) a = a[:index] + a[index:].replace("hello","hi",1) 时间接近 0.4。这不会使用 re。也更快。谢谢
  • 你只关注这个特定的例子。如果出现的次数更多,它将在没有循环的情况下失败。
  • 不,我猜你是对的。
【解决方案2】:

关于澄清,您应该以更具体的方式提出您的问题。如果没有很好的解释,就无法回答您的问题。但是因为你是新人,所以我会按照你所说的我所理解的来回答你。

import re

def replaceTheNTH(str, substr, substitute, N)
    wh = [m.start() for m in re.finditer(substr, str)][N-1]
    before = str[:wh]

    after = str[wh:]
    after = aft.replace(substr, substitute, 1)
    newString = before + after
    print newString

调用此方法将对您有所帮助。您可以替换较大字符串中出现的 n 次 substr。对于你的情况,你可以称之为

replaceTheNTH(a,'hello','hi',2)

【讨论】:

    【解决方案3】:

    我只是给你一个实现你想要的技巧。

    a = "hello world, hello there, hello python"
    a = a.replace("hello","hi",2).replace("hi","hello",1)
    print(a)
    

    那么,第二行到底是做什么的,它将前两次出现的 hello 替换为 hi,然后将第一次出现的 hi 替换为 hello。从而得到你想要的输出。

    或者你也可以去其他方式,如下:

    a = "hello world, hello there, hello python"
    index = a.find("hello",2)    
    a = a[:index] + a[index:].replace("hello","hi",1)
    print(a)
    

    因此您可以将其中任何一个用于您的目的。

    【讨论】:

      【解决方案4】:

      这应该可以正常工作:

      a = "hello world, hi there, hello python"
      

      替换整个字符串快速,易于编写且易于理解。


      假设,有人问如何替换:

      “Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in谴责 voluptate velit esse cillum dolore eu fugiat nulla pariatur。Exceptioneur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum。"

      “Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illoinvente veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit , sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam enimerat quat. ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, velturillum qui dolorem eum fugiat quo voluptas nulla paria /p>

      有人想推荐使用re、字符串操作或其他花哨的东西吗?

      【讨论】:

      • 大声笑!这里发生了什么?!
      • 虽然很有趣,但这并不是一个真正的答案......(我明白你想要表达的意思,但最好将问题关闭为“不清楚”(或同等原因))。
      • @cs95 我已经投票决定关闭,但是对于 OP 来说,在没有解释的情况下关闭可能有点难以理解。
      • LMAO 好笑!!
      【解决方案5】:

      虽然字符串是不可变的(不能改变它们),但我们仍然可以操作它们:

      a = a[:13] + "hi" + a[18:]
      

      【讨论】:

      • 这不是解决方案。您需要指定如何找到 13 和 18 值。如果它不是你好,而是嘿。这将失败。我建议的编辑是使用 find 函数来获取索引。
      猜你喜欢
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 2018-09-20
      • 2016-02-14
      相关资源
      最近更新 更多